http://poj.org/problem?id=3259
2.Idea
Using Bellman-Ford algorithm to detect negative loop in the graph.
3.Source
#define MAX_E 10004
#define MAX_V 2003
struct edge { int from, to, cost; } es[MAX_E];
int V, E;
int d[MAX_V];
bool find_negative_loop() //Bellman-Ford
{
memset(d, 0, sizeof d);
for (int i = 0; i < V; i++) {
for (int j = 0; j < E; j++) {
edge e = es[j];
if (d[e.to] > d[e.from] + e.cost) {
d[e.to] = d[e.from] + e.cost;
if (i == V - 1) return true;
}
}
}
return false;
}
int main()
{
int t;
int x, y, z, cnt = 0;
cin >> t;
while (t--) {
int n, m, w;
cin >> n >> m >> w;
V = n;
E = m * 2 + w;
cnt = 0;
for (int i = 0; i < m; i++) {
cin >> x >> y >> z;
x--; y--;
es[cnt].from = x;
es[cnt].to = y;
es[cnt].cost = z;
cnt++;
es[cnt].to = x;
es[cnt].from = y;
es[cnt].cost = z;
cnt++;
}
for (int i = 0; i < w; i++) {
cin >> x >> y >> z;
x--; y--;
es[cnt].from = x;
es[cnt].to = y;
es[cnt].cost = -z;
cnt++;
}
if (find_negative_loop()) cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}
No comments:
Post a Comment