原始的Bellman--ford算法。
#include <iostream>
#include <cstdio>#include <algorithm>
#include <cstdio>
#include <map>
#include <vector>
using namespace std;
const int INF_DIST = 1 << 20;
const int maxn_node = 510;
struct edge{
int weight, end;
};
vector<edge> nod[maxn_node];
int dist[maxn_node];
int n, m, w;
void debug() {
cout << "..." << endl;
for(int i = 0; i < n; i++) {
cout << i << " " << dist[i] << endl;
}
}
bool bellman_ford(int s) {
for(int i = 0; i < n; i++) {
if(i == s) dist[i] = 0;
else dist[i] = INF_DIST;
}
//debug();
for(int i = 1; i < n; i++) {
for(int j = 0; j < n; j++) {
for(int k = 0; k < nod[j].size(); k++) {
//cout << "*** " << dist[ nod[j][k].end ] << " " << dist[j] << " " << nod[j][k].weight << endl;
dist[ nod[j][k].end ] = min(dist[ nod[j][k].end ], dist[j] + nod[j][k].weight);
}
}
}
//debug();
for(int i = 0; i < n; i++) {
for(int j = 0; j < nod[i].size(); j++) {
//cout << "&& " << dist[ nod[i][j].end ] << " " << dist[i] << " " << nod[i][j].weight << endl;
if(dist[i] + nod[i][j].weight < dist[ nod[i][j].end ]) return false;//有负环
}
}
return true; //无负环
}
int main() {
int F;
scanf("%d", &F);
while(F--) {
scanf("%d%d%d", &n, &m, &w);
for(int i = 0; i < n; i++) {
nod[i].clear();
}
for(int i = 0; i < m; i++) {
int a, b, c;
scanf("%d%d%d", &a, &c, &b);
a--; c--;
edge tmp;
tmp.end = c; tmp.weight = b;
nod[a].push_back(tmp);
tmp.end = a; tmp.weight = b;
nod[c].push_back(tmp);
}
for(int i = 0; i < w; i++) {
int a, b, c;
scanf("%d%d%d", &a, &c, &b);
a--; c--;
edge tmp;
tmp.end = c; tmp.weight = -b;
nod[a].push_back(tmp);
}
if(bellman_ford(0)) cout << "NO" << endl;
else cout << "YES" << endl;
}
return 0;
}