70求调!(5 9 10)
查看原帖
70求调!(5 9 10)
854485
Tsr0409楼主2024/8/1 17:10
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 9;
using ll = long long;
const ll inf = 1e9;

struct Edge
{
    ll v, w;
};

int n, m;
vector<Edge> e[N];
int dis[N];
int cnt[N], vis[N]; // cnt 记录变数,判负环,vis 标记是否在队中
queue<int> q;       // 队列存储需要更新的点

bool spfa()
{
    // 两行初始化,不要忘记
    memset(dis, inf, sizeof(dis));
    memset(cnt, 0, sizeof(cnt));
    memset(vis, 0, sizeof(vis));
    dis[1] = 0;
    vis[1] = 1;
    q.push(1);
    while (!q.empty())
    {
        int u = q.front();
        q.pop();
        vis[u] = 0;
        for (auto ed : e[u]) // 更新所有边
        {
            int v = ed.v, w = ed.w;
            if (dis[v] > dis[u] + w) // 如果能被更新,更新且入队
            {
                dis[v] = dis[u] + w;
                cnt[v] = cnt[u] + 1; // 记录边数
                if (cnt[v] >= n)
                    return true; // 出现负环,退出

                if (!vis[v])
                {
                    q.push(v);
                    vis[v] = 1;
                }
            }
        }
    }
    return false;
}

void solve()
{
    for (int i = 1; i <= n; i++)
        e[i].clear();
    cin >> n >> m;
    for (int i = 1; i <= m; ++i)
    {
        int u, v;
        int w;
        cin >> u >> v >> w;
        if (w >= 0)
        {
            e[u].push_back({v, w});
            e[v].push_back({u, w});
        }
        else
        {
            e[u].push_back({v, w});
        }
    }
    if (spfa())
    {
        cout << "YES" << endl;
    }
    else
    {
        cout << "NO" << endl;
    }

    //     for (int i = 1; i <= n; ++i)
    //         cout << dis[i] << ' ';
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    int T = 1;
    cin >> T;
    while (T--)
    {
        solve();
    }
    return 0;
}
2024/8/1 17:10
加载中...