标签:
题目大意:农夫有F个农场,每个农场有N块田,田与田之间有M条道路,有W个虫洞。从虫洞过去,可以时光倒流。求能否见到最开始的自己。
解题思路:看是否能形成负圈
1 #include<iostream> 2 #include<cstring> 3 using namespace std; 4 5 #define MAX_V 6565 6 7 struct edge 8 { 9 int from,to,cost; 10 //有需要edge的数组时要加上这个无参构造函数 11 edge(){} 12 edge(int from,int to,int cost) 13 { 14 this->from=from; 15 this->to=to; 16 this->cost=cost; 17 } 18 }; 19 20 edge es[MAX_V]; 21 int V,E; 22 int d[MAX_V]; 23 24 bool find_negative_loop() 25 { 26 //找负圈要加 27 memset(d,0,sizeof(d)); 28 for(int k=0;k<V;k++) 29 { 30 for(int i=0;i<E;i++) 31 { 32 edge e=es[i]; 33 if(d[e.to]>d[e.from]+e.cost) 34 { 35 d[e.to]=d[e.from]+e.cost; 36 if(k==V-1) 37 { 38 return true; 39 } 40 } 41 } 42 } 43 return false; 44 } 45 46 int main() 47 { 48 int T; 49 cin>>T; 50 while(T--) 51 { 52 int M,W; 53 cin>>V>>M>>W; 54 E=0; 55 //注意无向图要重复一遍 56 for(int i=0;i<M;i++) 57 { 58 int from,to,cost; 59 cin>>from>>to>>cost; 60 from--; 61 to--; 62 es[E].from=from; 63 es[E].to=to; 64 es[E].cost=cost; 65 E++; 66 es[E].from=to; 67 es[E].to=from; 68 es[E].cost=cost; 69 E++; 70 } 71 for(int i=0;i<W;i++) 72 { 73 int from,to,cost; 74 cin>>from>>to>>cost; 75 from--; 76 to--; 77 es[E].from=from; 78 es[E].to=to; 79 es[E].cost=-cost; 80 E++; 81 } 82 if(find_negative_loop()) 83 { 84 cout<<"YES"<<endl; 85 } 86 else 87 { 88 cout<<"NO"<<endl; 89 } 90 } 91 return 0; 92 }
标签:
原文地址:http://www.cnblogs.com/xlsryj/p/4916499.html