求助只能过样例
查看原帖
求助只能过样例
406075
Qimu47楼主2022/8/11 12:12
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 100010;

int n,m;
int h[N],w[N],ne[N],e[N],idx;
int dist[N],cnt[N];
bool st[N];

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

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

int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        cin>>n>>m;
        memset(h,-1,sizeof h);
        while (m -- ){
            int a,b,c;
            cin>>a>>b>>c;
            if(c>=0)
            {
                add(a, b, c);
                add(b, a, c);
            }
            else add(a, b, c);
        }
        spfa();
        if(spfa()) puts("Yes");
        else puts("No");
    }
    return 0;
}
2022/8/11 12:12
加载中...