洛谷—— P3385 【模板】負環
阿新 • • 發佈:2017-08-19
next i++ bre 表示 一個 ace amp 存在 algo
輸出樣例#1:
題目描述
暴力枚舉/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,M,|w|≤200 000;1≤a,b≤N;T≤10 建議復制輸出格式中的字符串。
此題普通Bellman-Ford或BFS-SPFA會TLE
spfa判負環模板
判斷有無負環:如果某個點進入隊列的次數超過N次則存在負環(SPFA無法處理帶負環的圖)
代碼:
#include<cstdio> #include<cstring> #include<cstdlib> #include<iostream> #include<algorithm> #defineN 200010 using namespace std; bool vis[N],vist; int n,m,t,x,y,z,tot,head[N],dis[N]; int read() { int x=0,f=1; char ch=getchar(); while(ch<‘0‘||ch>‘9‘){if(ch==‘-‘)f=-1; ch=getchar();} while(ch>=‘0‘&&ch<=‘9‘){x=x*10+ch-‘0‘; ch=getchar();} return x*f; } struct Edge {int to,dis,from,next; }edge[N<<1]; int add(int x,int y,int z) { tot++; edge[tot].to=y; edge[tot].dis=z; edge[tot].next=head[x]; head[x]=tot; } void begin() { tot=vist=0; memset(dis,0,sizeof(dis)); memset(head,0,sizeof(head)); memset(vis,false,sizeof(vis)); } int spfa(int s) { vis[s]=true; for(int i=head[s];i;i=edge[i].next) { int t=edge[i].to; if(dis[s]+edge[i].dis<dis[t]) { dis[t]=dis[s]+edge[i].dis; if(vis[t]||vist) { vist=true; break; } spfa(t); } } vis[s]=false; } int main() { t=read(); while(t--) { n=read(),m=read();begin(); for(int i=1;i<=m;i++) { x=read(),y=read(),z=read(); add(x,y,z); if(z>=0) add(y,x,z); } for(int i=1;i<=n;i++) { spfa(i); if(vist) break; } if(vist) printf("YE5\n"); else printf("N0\n"); } return 0; }
洛谷—— P3385 【模板】負環