POJ 2240
POJ2240
题目大意:求负环
解:尼玛这有自环的,所以要u := q[head之后马上取消visit标记
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 const
2 maxn=30;
3 bilibili=maxlongint >> 1;
4 type
5 data=record
6 dest, next: longint;
7 cost: double;
8 end;
9 var
10 edge: array[1..maxn*maxn]of data;
11 a: array[1..maxn]of string;
12 vect: array[1..maxn]of longint;
13 dist: array[1..maxn]of double;
14 s, tot, n, m: longint;
15 flag : boolean;
16 function find(x: string): longint;
17 var
18 i: longint;
19 begin
20 for i := 1 to n do
21 if a[i]=x then exit(i);
22 end;
23
24 procedure add(x, y: longint; z: double);
25 begin
26 inc(tot);
27 with edge[tot] do
28 begin
29 dest := y;
30 cost := z;
31 next := vect[x];
32 vect[x] := tot;
33 end;
34 end;
35
36 procedure init;
37 var
38 i, j, x, y, k: longint;
39 z: double;
40 c: char;
41 st: string;
42 begin
43 inc(s);
44 readln(n);
45 if n=0 then
46 begin
47 close(input);
48 close(output);
49 halt;
50 end;
51 fillchar(vect, sizeof(vect), 0);
52 flag := false;
53 tot := 0;
54
55 for i := 1 to n do readln(a[i]);
56 readln(m);
57 for i := 1 to m do
58 begin
59 read(c);
60 st := '';
61 while c<>' ' do
62 begin
63 st := st + c;
64 read(c);
65 end;
66 x := find(st);
67 st := '';
68 read(z);
69 read(c);
70 st := '';
71 read(c);
72 while not(eoln) do
73 begin
74 st := st + c;
75 read(c);
76 end;
77 st := st + c;
78 y := find(st);
79 add(x, y, z);
80 readln;
81 end;
82 end;
83
84 procedure spfa(b, e: longint);
85 var
86 q: array[1..maxn+10]of longint;
87 key: array[1..maxn]of longint;
88 visit: array[1..maxn]of boolean;
89 head, tail, i, u: longint;
90 begin
91 fillchar(dist, sizeof(dist), 0);
92 fillchar(visit, sizeof(visit), 0);
93 fillchar(key, sizeof(key), 0);
94 head := 0;
95 tail := 1;
96 q[1] := b;
97 dist[b] := 1000;
98 visit[b] := true;
99 while head<>tail do
100 begin
101 head := head mod (maxn+10) +1;
102 u := q[head];
103 visit[u] := false;
104 if key[u]>=n then
105 begin
106 flag := true;
107 exit;
108 end;
109 inc(key[u]);
110 i := vect[u];
111 while i<>0 do
112 with edge[i] do
113 begin
114 if dist[u] * cost>dist[dest] then
115 begin
116 dist[dest] := dist[u] * cost;
117 if not visit[dest] then
118 begin
119 visit[dest] := true;
120 tail := tail mod (maxn+10) +1;
121 q[tail] := dest;
122 end;
123 end;
124 i := next;
125 end;
126 end;
127 flag := false;
128 end;
129
130 procedure print;
131 begin
132 write('Case ');
133 write(s, ': ');
134 if flag then writeln('Yes')
135 else writeln('No');
136 end;
137
138 procedure main;
139 var
140 i, j, k: longint;
141 begin
142 s := 0;
143 while true do
144 begin
145 init;
146 readln;
147 i := 0;
148 while (not flag)and(i<n) do
149 begin
150 inc(i);
151 spfa(i, i);
152 end;
153 print;
154 end;
155 end;
156
157 begin
158 assign(input,'aaa.in'); reset(input);
159 main;
160 //close(input);
161 end.