「P3385」【模板】負環(spfa
阿新 • • 發佈:2018-11-03
題目描述
暴力列舉/SPFA/Bellman-ford/奇怪的貪心/超神搜尋
輸入輸出格式
輸入格式:
第一行一個正整數T表示資料組數,對於每組資料:
第一行兩個正整數N M,表示圖有N個頂點,M條邊
接下來M行,每行三個整數a b w,表示a->b有一條權值為w的邊(若w<0則為單向,否則雙向)
輸出格式:
共T行。對於每組資料,存在負環則輸出一行"YE5"(不含引號),否則輸出一行"N0"(不含引號)。
輸入輸出樣例
輸入樣例#1: 複製2 3 4 1 2 2 1 3 4 2 3 1 3 1 -3 3 3 1 2 3 2 3 4 3 1 -8
N0 YE5
說明
n\leq 2000n≤2000m\leq 3000m≤3000-10000\leq w\leq 10000−10000≤w≤10000T\leq 10T≤10建議複製輸出格式中的字串。 本題資料感謝@negiizhao的精心構造,請不要使用玄學演算法 本題資料有更新
題解
列舉每個點,如果該點未被遍歷過,則以其為起點跑spfa。(防止圖不連通
跑的過程中記一下每個點被經歷的次數,如果被經歷(學術說法鬆弛?)了超過n次,說明這裡出現了負環。
算是spfa的一個小技巧?
————————————
然後是年度悲情大戲之——我的STLqueue不可能這麼慢↓
我的媽我這麼愛用的STLqueue這麼慢?!!
老姐你把我的時間直接拖長了一倍不止啊?!!(氣哭
還以為自己哪裡寫的太醜了......
1 /* 2 qwerta 3 P3385 【模板】負環 Accepted 4 100 5 程式碼 C++,1.24KB 6 提交時間 2018-11-03 15:37:36 7 耗時/記憶體 1759ms, 15192KB 8 */ 9 #include<iostream> 10 #include<cstring> 11 #include<cstdio> 12 #include<queue> 13using namespace std; 14 struct emm{ 15 int e,f,l; 16 }a[6003]; 17 int h[2003]; 18 int tot; 19 void con(int x,int y,int l) 20 { 21 //cout<<"con "<<x<<" "<<y<<" "<<l<<endl; 22 a[++tot].f=h[x]; 23 h[x]=tot; 24 a[tot].e=y; 25 a[tot].l=l; 26 return; 27 } 28 const int INF=1e9+7; 29 int d[2003]; 30 int c[2003]; 31 bool sf[2003]; 32 bool vis[2003]; 33 int q[4000003];//時間減半的手寫佇列 34 int main() 35 { 36 //freopen("a.in","r",stdin); 37 int t; 38 scanf("%d",&t); 39 while(t--) 40 { 41 tot=0; 42 memset(h,0,sizeof(h)); 43 int n,m; 44 scanf("%d%d",&n,&m); 45 for(int i=1;i<=m;++i) 46 { 47 int x,y,l; 48 scanf("%d%d%d",&x,&y,&l); 49 if(l<0) 50 con(x,y,l); 51 else 52 con(x,y,l),con(y,x,l); 53 } 54 int flag=0; 55 memset(d,127,sizeof(d)); 56 memset(c,0,sizeof(c)); 57 memset(vis,0,sizeof(vis)); 58 for(int s=n;s>=1&&!flag;--s) 59 if(!vis[s]) 60 { 61 memset(sf,0,sizeof(sf)); 62 d[s]=0;sf[s]=1;q[1]=s; 63 int l=0,r=1; 64 while(l<r&&!flag) 65 { 66 int x=q[++l]; 67 vis[x]=1; 68 for(int i=h[x];i;i=a[i].f) 69 if(d[a[i].e]>d[x]+a[i].l) 70 { 71 d[a[i].e]=d[x]+a[i].l; 72 c[a[i].e]++; 73 if(c[a[i].e]>=n){flag++;break;} 74 if(!sf[a[i].e]) 75 { 76 sf[a[i].e]=1; 77 q[++r]=a[i].e; 78 } 79 } 80 sf[x]=0; 81 } 82 d[s]=INF; 83 } 84 if(flag)cout<<"YE5"<<endl; 85 else cout<<"N0"<<endl; 86 } 87 return 0; 88 }