20pts,g了好久想不出来,求救
查看原帖
20pts,g了好久想不出来,求救
783346
IsacBieber楼主2024/8/5 11:04
#include<bits/stdc++.h>
using namespace std;
using pii = pair <int,int>;
bool st[2001];
int n, m, d[2001], cnt[2001];
vector <vector<pii>> e(2001);
queue <int> q;
bool spfa()
{
    for(int i=1;i<=n;i++)//初始化距离,入队状态,最短路边数 
    {
        d[i] = 0x3f3f3f3f;
        st[i] = cnt[i] = 0;
    }
    d[1] = 0;
    q = queue <int> ();//清空队列
    st[1] = 1;
    q.push(1);
    while(q.size())
    {
        int top = q.front();
        q.pop();
        st[top] = 0; 
        for(auto x:e[top])//更新队首点的出边
        {
            if(d[x.first]>d[top]+x.second)
            {
                d[x.first] = d[top] + x.second;
                cnt[x.first] = cnt[top] + 1;
                if(cnt[x.first]>=n) return true;//最短路边数>=n有负环
                if(!st[x.first])
                {
                    st[x.first] = 1;
                    q.push(x.first);
                }
            }
        }
    }
    return false;
}
void solve()
{
    cin>>n>>m;
    e.clear();//清空vector
    for(int i=1,a,b,w;i<=m;i++)//存边
    {
        cin>>a>>b>>w;
        e[a].emplace_back(make_pair(b,w));
        if(w>=0) e[b].emplace_back(make_pair(a,w));
    } 
    cout<<(spfa()?"YES\n":"NO\n");
}
int main(void)
{
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    int t;
    cin>>t;
    while(t--) solve();
    return 0;
}
2024/8/5 11:04
加载中...