Best Picnic Ever LightOJ - 1111
K people are having a picnic. They are initially in N cities, conveniently numbered from 1 to N. The roads between cities are connected by M one-way roads (no road connects a city to itself).
Now they want to gather in the same city for their picnic, but (because of the one-way roads) some people may only be able to get to some cities. Help them by figuring out how many cities are reachable by all of them, and hence are possible picnic locations.
Input
Input starts with an integer T (≤ 10), denoting the number of test cases.
Each case starts with three integers K (1 ≤ K ≤ 100), N (1 ≤ N ≤ 1000), M (1 ≤ M ≤ 10000). Each of the next K lines will contain an integer (1 to N) denoting the city where the ith person lives. Each of the next M lines will contain two integers u v (1 ≤ u, v ≤ N, u ≠ v) denoting there is a road from u to v.
Output
For each case, print the case number and the number of cities that are reachable by all of them via the one-way roads.
Sample Input
1
2 4 4
2
3
1 2
1 4
2 3
3 4
Sample Output
Case 1: 2
第一个人能到达的每一个点加一,表示这个点被一个人走过。然后第二个,第三个。。。直至第K个人。最后一个for循环,遍历所有的点,找到所有的被K个人走过的点,就是answer!
1 #include<cstdio> 2 #include<string> 3 #include<cstring> 4 #include<queue> 5 #include<iostream> 6 #include<algorithm> 7 #define MAX 10005 8 using namespace std; 9 struct edge{ 10 int to; 11 int next; 12 }e[MAX]; 13 int head[MAX],vis[1002],dis[1002]; 14 int T,K,N,M; 15 int tot; 16 17 void init() 18 { memset(head,-1,sizeof(head)); 19 tot=0; 20 } 21 void addedge(int u,int v) 22 { e[tot].to=v; 23 e[tot].next=head[u]; 24 head[u]=tot++; 25 } 26 void DFS(int start) 27 { 28 memset(vis,0,sizeof(vis)); 29 queue<int> q; 30 q.push(start); 31 vis[start]=1; 32 dis[start]+=1; 33 while(!q.empty()) 34 { int v=q.front(); 35 q.pop(); 36 for(int i=head[v];i!=-1;i=e[i].next) 37 { int t=e[i].to; 38 if(!vis[t]) 39 { vis[t]=1; 40 dis[t]+=1; 41 q.push(t); 42 } 43 } 44 } 45 } 46 int main() 47 { cin>>T; 48 for(int t=1;t<=T;t++) 49 { init(); 50 memset(dis,0,sizeof(dis)); 51 52 scanf("%d%d%d",&K,&N,&M); 53 int des[K]; 54 for(int i=0;i<K;i++) scanf("%d",&des[i]); 55 int u,v; 56 for(int i=0;i<M;i++) 57 { scanf("%d%d",&u,&v); 58 addedge(u,v); 59 } 60 for(int i=0;i<K;i++) 61 { DFS(des[i]); 62 } 63 int ans=0; 64 for(int i=1;i<=N;i++) 65 if(dis[i]==K) ans++; 66 printf("Case %d: %d\n",t,ans); 67 } 68 }