虫洞_poj3259_bellman_ford

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, FF farm descriptions follow.
Line 1 of each farm: Three space-separatedintegers respectively: NM, and W
Lines 2..M+1 of each farm: Three space-separated numbers (SET) 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 (SET) 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.

【解题思路】

【源代码】/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
n:=0;
for i:=1 to m do
begin
with a[i*2-1] do
begin
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;
next:=l[y];
l[y]:=i*2;
end;
end;
n:=m*2;
end;
begin
init;
if ford then
writeln('YES')
else
writeln('NO');
end.
``````

原文作者：Bellman - ford算法
原文地址: https://blog.csdn.net/jpwang8/article/details/51166997
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。