大佬们,为啥我这个错,这个题目不是问的从一开始到达的负环吗
查看原帖
大佬们,为啥我这个错,这个题目不是问的从一开始到达的负环吗
579961
JunBuJian楼主2022/7/8 18:38
#include<iostream>
#include<queue>
#include<cstring>

using namespace std;
const int N = 2e5 + 5;
int h[N],e[N],ne[N],w[N],idx;
int n,m,t;
int dist[N],cnt[N];
bool st[N];

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

bool spfa()
{
    queue<int> q;
    q.push(1);
    st[1] = true;
    
    
    while(q.size())
    {
        auto 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) return true;
               if(!st[j])
               {
                   q.push(j);
                   st[j] = true;
               }
            }
        }
    }
    return false;
}

int main()
{
    cin >> t;
    while(t --)
    {
        idx = 0;
        memset(h,-1,sizeof h);
        memset(cnt,0,sizeof cnt);
        memset(st,0,sizeof st);
        cin >> n >> m; 
        
        while(m --)
        {
            int a,b,c;
            cin >> a >> b >> c;
            add(a,b,c);
            
            if(c >= 0) 
               add(b,a,c);
        }
        
        if(spfa()) puts("YES");
        else puts("NO");
    }
    
    return 0;
}
2022/7/8 18:38
加载中...