Description
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个人,K 行下面是第K个人住在第几个城市。
给出M条路线有向图。求出一共有多少个城市可以一起聚餐
用dfs可以解答,也可以用bfs。
#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>
using namespace std;
int K,N,M,u,v;
bool vis[1005];
int people[105];
int sum[1005];
vector<int> city[1005];
void init(){
for(int i = 0 ; i <= 1004; i++)city[i].clear();
memset(sum,0,sizeof(sum));
}
void dfs(int n){
vis[n] = true;
sum[n]++;
int len = city[n].size();
for(int i = 0 ; i < len; i++)
if(!vis[city[n][i]])
dfs(city[n][i]);
}
int main(){
int T;
cin>>T;
for(int i = 1; i <= T;i++){
cin>>K>>N>>M;init();
for(int k = 0; k < K; k++)scanf("%d",&people[k]);
for(int m = 0; m < M; m++){
scanf("%d%d",&u,&v);
city[u].push_back(v);
}
for(int k = 0; k < K; k++){
memset(vis,false,sizeof(vis));
dfs(people[k]);
}
int c = 0;
for(int n = 1; n<=N;n++){
if(sum[n] == K)c++;
}
printf("Case %d: %d\n",i,c);
}
return 0;
}