首页 > 代码库 > POJ 3259 Wormholes
POJ 3259 Wormholes
/**POJ 3259 Wormholes*判断负权值回路*/#include <cstdio>#include <cstring>#include <queue>using namespace std;#define INF 10000000#define MAXN 600struct 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;}
POJ 3259 Wormholes
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。