1 条题解

  • 0
    @ 2025-3-8 10:00:58

    Bellman-Ford 做法,SPFA 做法见:https://oj.33dai.cn/p/P5960/solution

    #include <bits/stdc++.h>
    using namespace std;
    const int MAXN = 5000;
    const int INF = 2147483647;
    int n, m;
    int M; // 边的条数
    int u[MAXN * 2 + 5], v[MAXN * 2 + 5], w[MAXN * 2 + 5];
    int dis[MAXN + 1 + 5];
    int main()
    {
        ios::sync_with_stdio(false);
        cin.tie(0);
        cin >> n >> m;
        M = 0;
        for (int i = 1; i <= m; i++)
        {
            int op, a, b, c;
            cin >> op;
            if (op == 1)
            {
                cin >> a >> b >> c;
                // a-b>=c ~ b-a<=-c
                ++M;
                u[M] = a, v[M] = b, w[M] = -c;
            }
            if (op == 2)
            {
                cin >> a >> b >> c;
                // a-b<=c
                ++M;
                u[M] = b, v[M] = a, w[M] = c;
            }
            if (op == 3)
            {
                cin >> a >> b;
                // a=b ~ a-b<=0 , b-a<=0
                ++M;
                u[M] = b, v[M] = a, w[M] = 0;
                u[M] = a, v[M] = b, w[M] = 0;
            }
        }
        // Bellman-Ford
        for (int i = 1; i <= n; i++)
            dis[i] = 0; // 超级源点到每个点的距离都是 0
        for (int i = 1; i <= n; i++)
        {
            bool flag = true;
            for (int j = 1; j <= M; j++)
                if (dis[u[j]] + w[j] < dis[v[j]])
                {
                    flag = false;
                    dis[v[j]] = dis[u[j]] + w[j];
                }
            if (flag)
                break;
            if (i == n && !flag)
            {
                cout << "No";
                return 0;
            }
        }
        cout << "Yes";
        return 0;
    }
    
    
    • 1

    信息

    ID
    1789
    时间
    1000ms
    内存
    128MiB
    难度
    4
    标签
    递交数
    61
    已通过
    11
    上传者