Wormholes
【题目描述】
While exploring his many farms, Farmer Johnhas discovered a number of amazing wormholes. A wormhole is very peculiarbecause it is a one-way path that delivers you to its destination at a timethat 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 pathsand wormholes, and return to the starting field a time before his initialdeparture. Perhaps he will be able to meet himself :) .
To help FJ find out whether this ispossible or not, he will supply you with complete maps to F (1 ≤ F ≤ 5) ofhis farms. No paths will take longer than 10,000 seconds to travel and nowormhole can bring FJ back in time by more than 10,000 seconds.
【输入文件】
Line 1: A single integer, F. F farm descriptions follow.
Line 1 of each farm: Three space-separatedintegers respectively: N, M, and W
Lines 2..M+1 of each farm: Three space-separated numbers (S, E, T) that describe,respectively: a bidirectional path between S and E that requires T secondsto traverse. Two fields might be connected by more than one path.
Lines M+2..M+W+1 of each farm:Three space-separated numbers (S, E, T) that describe, respectively: A one way path from S to E thatalso moves the traveler back T seconds.
【输出文件】
Lines 1..F: For each farm, output”YES” if FJ can achieve his goal, otherwise output “NO” (donot include the quotes).
【样例输入】
2
3 3 1
1 2 2
1 3 4
2 3 1
3 1 3
3 2 1
1 2 3
2 3 4
3 1 8
【样例输出】
NO
YES
【样例说明】
For farm 1, FJ cannot travelback in time.
For farm 2, FJ could travel back in time by thecycle 1->2->3->1, arriving back at his starting location 1 secondbefore he leaves. He could start from anywhere on the cycle to accomplish this.
【解题思路】
由于存在负权边,就用Bellman_ford。题目简化一下,就是看所给的图中有没有负权回路,如果有的话,输出”YES”,否则,输出”NO”。
【源代码】/pas
type rec=record
x,y,next:longint;
t,w:real;
end;
var
f,n,m,s:longint;
d:array[1..6000]of real;
l:array[1..6000]of longint;
a:array[1..6000]of rec;
p:real;
function ford:boolean;
var i,k:longint;
begin
for i:=1 to n do d[i]:=0;
d[s]:=p;
for k:=1 to n-1 do
begin
ford:=false;
for i:=1 to n do
if (d[a[i].x]-a[i].t)*a[i].w>d[a[i].y] then
begin
d[a[i].y]:=(d[a[i].x]-a[i].t)*a[i].w;
ford:=true;
end;
if ford=false then exit(false);
end;
for i:=1 to n do
if (d[a[i].x]-a[i].t)*a[i].w>d[a[i].y] then
exit(true);
end;
procedure init;
var
i:longint;
x,y,w:Longint;
begin
readln(n,m,s,p);
n:=0;
for i:=1 to m do
begin
with a[i*2-1] do
begin
read(x,y,w,t);
next:=l[x];
l[x]:=i*2-1;
end;
with a[i*2] do
begin
x:=a[i*2-1].y;
y:=a[i*2-1].x;
readln(w,t);
next:=l[y];
l[y]:=i*2;
end;
end;
n:=m*2;
end;
begin
init;
if ford then
writeln('YES')
else
writeln('NO');
end.