LightOJ - 1111 Best Picnic Ever

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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值