POJ 3259 Wormholes (bellman_ford)

来源:互联网 发布:mysql exists 代替 in 编辑:程序博客网 时间:2024/05/18 20:48

题目链接:~( ̄▽ ̄~)(~ ̄▽ ̄)~

资料链接:\(▔▽▔)/



code:

#include <stdio.h>int n = 0, m = 0, w = 0, count = 0;typedef struct{int u, v, weight;}node;node edge[6000];int bellman_ford(){int i = 0, j = 0, dis[505], u = 0, v = 0, weight = 0, flag = 0;for(i = 0; i<=n; i++)dis[i] = 1234567890;dis[1] = 0;for(i = 0; i<n-1; i++)//循环时循环n-1个点,应为每次最少找出1条最短边,共有n-1条边{flag = 1;for(j = 0; j<count; j++){u = edge[j].u;  v = edge[j].v;  weight = edge[j].weight;if(dis[v]>dis[u]+weight){dis[v] = dis[u]+weight;flag = 0;}}if(flag)break;}for(i = 0; i<count; i++)//有负权回路时会无限循环{u = edge[i].u;  v = edge[i].v;  weight = edge[i].weight;if(dis[v]>dis[u]+weight)return 1;}return 0;}int main(){int i = 0, t = 0,s = 0, e = 0, text = 0;scanf("%d",&text);while(text--){count = 0;scanf("%d %d %d",&n,&m,&w);for(i = 0; i<m; i++){scanf("%d %d %d",&s, &e, &t);edge[count].u = s;edge[count].v = e;edge[count++].weight = t;edge[count].v = s;edge[count].u = e;edge[count++].weight = t;}for(i = 0; i<w; i++){scanf("%d %d %d",&s,&e,&t);edge[count].u = s;edge[count].v = e;edge[count++].weight = -t;}if(bellman_ford())printf("YES\n");elseprintf("NO\n");}return 0;}