# POJ-3259 Wormholes (bellman_ford算法)

## 代码：

#include <iostream>
#include <algorithm>
#include <stdio.h>

#define MAXNUM 0x7ffffff

using namespace std;

struct node
{
int begin;
int end;
int cost;
} edge[6000];

int n, m, w, count_;
int maxn[550];

bool bellman_ford()
{
bool flag;
int x, y, cost;

for (int i = 1; i <= n; i++) {
maxn[i] = MAXNUM;
}
maxn[1] = 1;
for (int i = 1; i <= n; i++) {
flag = true;
for (int j = 1; j <= count_; j++) {
x = edge[j].begin;
y = edge[j].end;
cost = edge[j].cost;
if (maxn[x] + cost < maxn[y]) {
maxn[y] = maxn[x] + cost;
flag = false;
}
}
if (flag)
break;
}
for (int i = 1; i <= count_; i++) {
x = edge[i].begin;
y = edge[i].end;
cost = edge[i].cost;
if (maxn[y] > maxn[x] + cost)
return true;
}
return false;
}

int main()
{
int t;
int x, y, cost;

scanf("%d", &t);
while (t--) {
count_ = 0;
scanf("%d%d%d", &n, &m, &w);
for (int i = 1; i <= m; i++) {
scanf("%d%d%d", &x, &y, &cost);
edge[++count_].begin = x;
edge[count_].end = y;
edge[count_].cost = cost;
edge[++count_].begin = y;
edge[count_].end = x;
edge[count_].cost = cost;
}
for (int i = 1; i <= w; i++) {
scanf("%d%d%d", &x, &y, &cost);
edge[++count_].begin = x;
edge[count_].end = y;
edge[count_].cost = -cost;
}
//        for (int i = 1; i <= count_; i++) {
//            printf("begin:%d\tend:%d\tcost:%d\n", edge[i].begin, edge[i].end, edge[i].cost);
//        }
if (bellman_ford()) {
printf("YES\n");
} else {
printf("NO\n");
}
}

return 0;
}

原文作者：Bellman - ford算法
原文地址: https://blog.csdn.net/qq_32685139/article/details/52862120
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。