输出图中所有负环上的点

#include <cstring>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;

const int INF = 0x3f3f3f3f;
const int MAX_V = 100 + 1;
int V, m;
typedef pair<int, int> P;
struct edge {
    int to, cost;
    edge(int t, int c) {
        to = t;
        cost = c;
    }
};
vector<edge> map[MAX_V];
int d[MAX_V], book[MAX_V], numv[MAX_V];
//Bellmanford是将从起点st开始的最短路求出来,在负环里的点距离直接变为-INF,且V次入队以后不再入队。
void Bellmanford(int st) {
    queue<int> q;
    fill(d, d + V + 1, INF);
    memset(book, 0, sizeof(book));
    memset(numv, 0, sizeof(numv));
    d[st] = 0, book[st] = 1, numv[st]++;
    q.push(st);
    while (q.size()) {
        int tmp = q.front();
        q.pop();
        book[tmp] = 0;
        for (auto i : map[tmp]) {
            if (d[i.to] > d[tmp] + i.cost) {
                d[i.to] = d[tmp] + i.cost;
                if (!book[i.to]) {
                    book[i.to] = 1;
                    numv[i.to]++;
                    if (numv[i.to] >= V)
                        d[i.to] = -INF;
                    if (numv[i.to] <= V)
                        q.push(i.to);
                }
            }
        }
    }
}
int main() {
    cin >> V >> m;
    while (m--) {
        int a, b, c;
        cin >> a >> b >> c;
        map[a].push_back(edge(b, c));
        map[b].push_back(edge(a, c));
    }
    int ans[V + 1];
    memset(ans, 0, sizeof(ans));
    //如果在负环内的点,到每个点的距离必然是-INF
    for (int i = 1; i <= V; i++) {
        Bellmanford(i);
        for (int j = 1; j <= V; j++) {
            if (d[j] != -INF)
                ans[i] = 1;
        }
    }
    for (int i = 1; i <= V; i++)
        if (!ans[i])
            cout << i << " ";
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值