为什么有个点一直不过,我用的虚拟原点做法,大佬帮忙看看
查看原帖
为什么有个点一直不过,我用的虚拟原点做法,大佬帮忙看看
392004
sm76楼主2021/11/30 08:43
#include <bits/stdc++.h>

using namespace std;

const int M = 3e3 + 15;
const int N = 2e3 + 15;

struct Edge {
    int ne, to, val;
}edge[M * 2];
int head[N], cnt;

queue<int> q;
bool vis[N];
int dis[N];
int nums[N];

int t, n, m;

void add(int from, int to, int val) {
    edge[++cnt].ne = head[from];
    edge[cnt].to = to;
    edge[cnt].val = val;
    head[from] = cnt;
}

bool SPFA() {
    memset(dis, 0x3f3f3f, sizeof(dis));
    memset(nums, 0, sizeof(nums));
    memset(vis, true, sizeof(vis));
    while (!q.empty()) {
        q.pop();
    }
    
    for (int i = 1; i <= n; i++) {
        q.push(i);
    }
    while (!q.empty()) {
        int t = q.front();
        vis[t] = false;
        q.pop();
        for (int i = head[t]; i; i = edge[i].ne) {
            int y = edge[i].to;
            if (dis[y] > dis[t] + edge[i].val) {
                dis[y] = dis[t] + edge[i].val;
                nums[y] = nums[t] + 1;
                if (nums[y] == n) {
                    return true;
                }
                if (!vis[y]) {
                    q.push(y);
                    vis[y] = true;
                }
            }
        }
    }
    return false;
}

int main() {
    cin >> t;
    while (t--) {
        memset(head, 0, sizeof(head));
        cnt = 0;
        cin >> n >> m;
        for (int i = 1; i <= m; i++) {
            int u, v, w;
            cin >> u >> v >> w;
            add(u, v, w);
            if (w >= 0) {
                add(v, u, w);
            }
        }
        if (SPFA()) {
            cout << "YES" << endl;
        }
        else {
            cout << "NO" << endl;
        }
    }
    system("pause");
    return 0;
}
2021/11/30 08:43
加载中...