首页 > 代码库 > 1648: [Usaco2006 Dec]Cow Picnic 奶牛野餐
1648: [Usaco2006 Dec]Cow Picnic 奶牛野餐
1648: [Usaco2006 Dec]Cow Picnic 奶牛野餐
Time Limit: 5 Sec Memory Limit: 64 MBSubmit: 432 Solved: 270
[Submit][Status]
Description
The cows are having a picnic! Each of Farmer John‘s K (1 <= K <= 100) cows is grazing in one of N (1 <= N <= 1,000) pastures, conveniently numbered 1...N. The pastures are connected by M (1 <= M <= 10,000) one-way paths (no path connects a pasture to itself). The cows want to gather in the same pasture for their picnic, but (because of the one-way paths) some cows may only be able to get to some pastures. Help the cows out by figuring out how many pastures are reachable by all cows, and hence are possible picnic locations.
Input
* Line 1: Three space-separated integers, respectively: K, N, and M * Lines 2..K+1: Line i+1 contains a single integer (1..N) which is the number of the pasture in which cow i is grazing. * Lines K+2..M+K+1: Each line contains two space-separated integers, respectively A and B (both 1..N and A != B), representing a one-way path from pasture A to pasture B.
第1行输入K,N,M.接下来K行,每行一个整数表示一只奶牛所在的牧场编号.接下来M行,每行两个整数,表示一条有向路的起点和终点
Output
* Line 1: The single integer that is the number of pastures that are reachable by all cows via the one-way paths.
所有奶牛都可到达的牧场个数
Sample Input
2
3
1 2
1 4
2 3
3 4
INPUT DETAILS:
4<--3
^ ^
| |
| |
1-->2
The pastures are laid out as shown above, with cows in pastures 2 and 3.
Sample Output
牧场3,4是这样的牧场.
HINT
Source
Silver
题解:尼玛这道题居然都被卡了一次——原因很逗比,因为中间BFS当此点访问过时应该跳过,结果我一开始脑抽写了个 if c[p^.g]=1 then continue; 仔细想想,当这种情况下p指针还没等跳到下一个就continue了啊,不死循环才怪!!!(phile:多大了还犯这种错!!!)。。。然后没别的了,就是对于每个牛都用BFS或者DFS来搜一编能够到达的点,然后没了——复杂度才O(K(N+M))肯定没问题。。。(所以一开始当我看到红色的TLE时真心被吓到了QAQ)
1 type 2 point=^node; 3 node=record 4 g:longint; 5 next:point; 6 end; 7 8 var 9 i,j,k,l,m,n,f,r:longint;10 P:point;11 a:array[0..1050] of point;12 b,c,d,e:array[0..1050] of longint;13 procedure add(x,y:longint);inline;14 var p:point;15 begin16 new(p);17 p^.g:=y;18 p^.next:=a[x];19 a[x]:=p;20 end;21 begin22 readln(e[0],n,m);23 for i:=1 to n do24 begin25 d[i]:=1;26 a[i]:=nil;27 end;28 for i:=1 to e[0] do29 readln(e[i]);30 for i:=1 to m do31 begin32 readln(j,k);33 add(j,k);34 end;35 for i:=1 to e[0] do36 begin37 fillchar(c,sizeof(c),0);38 fillchar(b,sizeof(b),0);39 c[e[i]]:=1;40 b[1]:=e[i];41 f:=1;r:=2;42 while f<r do43 begin44 p:=a[b[f]];45 while p<>nil do46 begin47 if c[p^.g]=0 then48 begin49 c[p^.g]:=1;50 b[r]:=p^.g;51 inc(r);52 end;53 p:=p^.next;54 end;55 inc(f);56 end;57 for j:=1 to n do58 d[j]:=d[j]*c[j];59 end;60 l:=0;61 for i:=1 to n do l:=l+d[i];62 writeln(l);63 end.
1648: [Usaco2006 Dec]Cow Picnic 奶牛野餐