Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 37906 | Accepted: 13954 |
Description
While exploring his many farms, Farmer John has discovered a number of amazing wormholes. A wormhole is very peculiar because it is a one-way path that delivers you to its destination at a time that is BEFORE you entered the wormhole! Each of FJ's farms comprises N (1 ≤ N ≤ 500) fields conveniently numbered 1..N, M (1 ≤ M ≤ 2500) paths, and W (1 ≤ W ≤ 200) wormholes.
As FJ is an avid time-traveling fan, he wants to do the following: start at some field, travel through some paths and wormholes, and return to the starting field a time before his initial departure. Perhaps he will be able to meet himself :) .
To help FJ find out whether this is possible or not, he will supply you with complete maps to F (1 ≤ F ≤ 5) of his farms. No paths will take longer than 10,000 seconds to travel and no wormhole can bring FJ back in time by more than 10,000 seconds.
Input
Output
Sample Input
23 3 11 2 21 3 42 3 13 1 33 2 11 2 32 3 43 1 8
Sample Output
NOYES
Hint
正常的path是双向的,有一定的消耗时间。虫洞是单向的,能够让时间倒流一定时间。问FJ能否找到一条路径,能够遇见之前的那个自己。
说白了就是找负环。
Bellman_ford模板题,用来对每一条边都进行松弛,然后看最后结果是否依然能够松弛。如果还能松弛,说明有负环;如果不能松弛了,就是没有负环。
代码:
#include#include #include #include #include #include #pragma warning(disable:4996)using namespace std;struct E{ int s; int e; int l;}edge[5205];int N,M,W,edge_num;int dis[505];void addedge(int start,int end,int len){ edge_num++; edge[edge_num].s=start; edge[edge_num].e=end; edge[edge_num].l=len;}bool bellman_ford(){ int i,j; for(i=1;i<=N-1;i++) { int flag=0; for(j=1;j<=edge_num;j++) { if(dis[edge[j].e]>dis[edge[j].s]+edge[j].l) { flag=1; dis[edge[j].e]=dis[edge[j].s]+edge[j].l; } } if(flag==0) break; } for(j=1;j<=edge_num;j++) { if(dis[edge[j].e]>dis[edge[j].s]+edge[j].l) { return true; } } return false;}int main(){ int i,start,end,len; int Test; cin>>Test; while(Test--) { edge_num=0; memset(dis,0,sizeof(dis)); cin>>N>>M>>W; for(i=1;i<=M;i++) { cin>>start>>end>>len; addedge(start,end,len); addedge(end,start,len); } for(i=1;i<=W;i++) { cin>>start>>end>>len; addedge(start,end,-len); } if(bellman_ford()) { cout<<"YES"<
版权声明:本文为博主原创文章,未经博主允许不得转载。