标签:
/*
*POJ 3259 Wormholes
*判断负权值回路
*/
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
#define INF 10000000
#define MAXN 600
struct ArcNode {
int to;
int weight;
ArcNode *next;
};
queue<int> q;
int N, M, W;
ArcNode *list[MAXN]; //每个顶点的边链表表头指针
int in[MAXN]; //每个顶点是否在队列
int count[MAXN]; //每个顶点入队列的次数
int dist[MAXN];
bool spfa(int src)
{
int i, u;
ArcNode *temp;
for (i = 1 ; i <= N; i++) {
dist[i] = INF;
in[i] = 0;
}
dist[src] = 0; in[src] ++;
q.push(src);
count[src] ++;
while ( !q.empty()) {
u = q.front();
q.pop();
in[u] --;
if (count[u] > N) //存在负权值回路
return true;
temp = list[u];
while (temp != NULL) {
int v = temp->to;
if (dist[v] > dist[u] + temp->weight) {
dist[v] = dist[u] + temp->weight;
if (!in[v]) {
q.push(v); in[v]++; count[v]++;
}
}
temp = temp->next;
}
}
return false;
}
int main()
{
int i, T;
int u, v, w;
scanf("%d", &T);
while (T--) {
scanf("%d%d%d", &N, &M, &W);
memset(list, 0, sizeof(list));
memset(in, 0, sizeof(in));
memset(count, 0, sizeof(count));
while (!q.empty()) {
q.pop();
}
ArcNode *temp;
for (i = 1; i <= M; i++) {
scanf("%d%d%d", &u, &v, &w);
temp = new ArcNode;
temp->to = v; temp->weight = w; temp->next = NULL;
if (list[u] == NULL) {
list[u] = temp;
} else {
temp->next = list[u]; list[u] = temp;
}
temp = new ArcNode;
temp->to = u; temp->weight = w; temp->next = NULL;
if (list[v] == NULL) {
list[v] = temp;
} else {
temp->next = list[v]; list[v] = temp;
}
}
for (i = 1; i <= W; i++) {
scanf("%d%d%d", &u, &v, &w);
temp = new ArcNode;
temp->to = v; temp->weight = -w; temp->next = NULL;
if (list[u] == NULL) {
list[u] = temp;
} else {
temp->next = list[u]; list[u] = temp;
}
}
if (spfa(1)) {
printf("YES\n");
} else {
printf("NO\n");
}
for (i = 1; i <= N; i++) {
temp = list[i];
while (temp != NULL) {
list[i] = temp->next; delete temp; temp = list[i];
}
}
}
return 0;
}
标签:
原文地址:http://www.cnblogs.com/subrshk/p/4248243.html