POJ 3259 Wormholes(spfa 判断负环)

 

有 n 个点,m 条无向边,t 条有向边,判断图是否存在负环 

const int N=1e4+5;
 
    int n,m,t;
    int i,j,k;
    int head[N],all=0;
    int d[N]; //点 i 到起点的距离
    int cnt[N]; //点 i 的入队次数
    bool vis[N];

struct node
{
    int to,next;
    int w;
}G[N];
void add(int u,int v,int w)
{
    G[all].w=w;
    G[all].to=v;
    G[all].next=head[u];
    head[u]=all++;
}
int SPFA(int s,int num)
{
    for(int i=1;i<=num;i++) vis[i]=0,d[i]=inf,cnt[i]=0;
    queue<int> q;
    vis[s]=1;
    d[s]=0;
    cnt[s]++;
    q.push(s);
    while(q.size()){
        int u=q.front();
        q.pop();
        vis[u]=0;
        for(int i=head[u];i!=-1;i=G[i].next){
            int v=G[i].to;
            int w=G[i].w;
            if(d[v]>d[u]+w){
                d[v]=d[u]+w;
                if(!vis[v]){
                    vis[v]=1;
                    q.push(v);
                    cnt[v]++;
                    if(cnt[v]>num) return 1;
                }
            }
        }
    }
    return 0;
}
int main()
{
    //IOS;
    rush(){
        sddd(n,m,t);
        ms(head,-1);
        all=0;
        for(i=1;i<=m;i++){
            int u,v,w;
            sddd(u,v,w);
            add(u,v,w);
            add(v,u,w);
        }
        while(t--){
            int u,v,w;
            sddd(u,v,w);
            add(u,v,-w);
        }
        int ans=SPFA(1,n);
        if(ans) puts("YES");
        else puts("NO");
    }
    //PAUSE;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值