P1993 小 K 的农场

点击查看代码
#include<bits/stdc++.h>
using namespace std;

const int N=1e4+10,M=5e4+10;
int dist[N],cnt[N],st[N];
int h[N],ne[M],e[M],w[M],idx;
int n,m;

void add(int u,int v,int c)
{
    w[idx]=c,e[idx]=v,ne[idx]=h[u],h[u]=idx++;
}

bool spfa()
{
    memset(dist,0x3f,sizeof dist);
    dist[0]=0;
    st[0]=true;
    queue<int> q;
    q.push(0);

    while(q.size()){
        int t =q.front();
        q.pop();
        st[t]=false;
        for(int i=h[t];~i;i=ne[i]){
            int j=e[i];
            if(dist[j]>dist[t]+w[i]){
                dist[j]=dist[t]+w[i];
                cnt[j]=cnt[t]+1;
                if(cnt[j]>=n+1) return true;
                if(!st[j]){
                    q.push(j);
                    st[j]=true;
                }
            }
        }
    }

    return false;
}

int main()
{
    ios::sync_with_stdio(0),cin.tie(0);
    cin>>n>>m;
    memset(h,-1,sizeof h);
    for(int i=1;i<=n;i++){
        add(0,i,0);
    }

    while(m--){
        int op,a,b,c;
        cin>>op;
        if(op==1){
        	cin>>a>>b>>c;
            add(a,b,-c);
        }else if(op==2){
        	cin>>a>>b>>c;
            add(b,a,c);
        }else{
        	cin>>a>>b;
            add(a,b,0);
            add(b,a,0);
        }
    }

    if(spfa()){
        cout<<"No"<<"\n";
    }else{
        cout<<"Yes"<<"\n";
    }

    return 0;
    
}
posted @ 2026-02-24 21:40  AnoSky  阅读(1)  评论(0)    收藏  举报