洛谷P3385 【模板】负环

SPFA 判负环

代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#define INF 0x3f3f3f3f
#define MAXN 2010
#define MAXM 6010
using namespace std;
int n,m,T,u,v,w,dis[MAXN],head[MAXN],tot,cnt[MAXN];
bool inq[MAXN];
struct Edge{
    int to,w,nxt;
}edge[MAXM];
void addedge(int u,int v,int w){
    edge[tot].to=v;edge[tot].w=w;
    edge[tot].nxt=head[u];head[u]=tot++;
}
bool spfa(){
    queue<int> q;q.push(1);
    memset(inq,false,sizeof(inq));
    inq[1]=true;
    memset(dis,INF,sizeof(dis));
    memset(cnt,0,sizeof(cnt));
    dis[1]=0;cnt[1]=1;
    while(!q.empty()){
        int u=q.front();q.pop();
        inq[u]=false;
        for(int i=head[u];i!=-1;i=edge[i].nxt){
            int v=edge[i].to,w=edge[i].w;
            if(dis[u]+w<dis[v]){
                dis[v]=dis[u]+w;
                if(!inq[v]){
                    q.push(v);inq[v]=true;
                    if(++cnt[v]>n)return false;
                }
            }
        }
    }
    return true;
}
int main(){
#ifdef WINE
    freopen("data.in","r",stdin);
#endif
    scanf("%d",&T);
    while(T--){
        memset(head,-1,sizeof(head));
        tot=0;
        scanf("%d%d",&n,&m);
        while(m--){
            scanf("%d%d%d",&u,&v,&w);
            addedge(u,v,w);
            if(w>=0)addedge(v,u,w);
        }
        if(spfa())printf("N0\n");
        else printf("YE5\n");
    }
    return 0;
}

在这里插入图片描述

posted @ 2020-04-05 22:14  winechord  阅读(78)  评论(0编辑  收藏  举报