Lightoj1111——Best Picnic Ever(dfs)

来源:互联网 发布:链轮设计软件 编辑:程序博客网 时间:2024/06/06 06:09

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
Output for Sample Input
1
2 4 4
2
3
1 2
1 4
2 3
3 4
Case 1: 2

k个人分布在1-N的城市中,城市之间是单向连接,求哪些城市能够使所有人都到达
简单的搜索,每次搜索的起点是有人在的城市,每搜到一个城市,该城市能到达的人数+1

#include <iostream>#include <cstring>#include <string>#include <vector>#include <queue>#include <cstdio>#include <set>#include <math.h>#include <algorithm>#include <queue>#include <iomanip>#include <map>#define INF 0x3f3f3f3f#define MAXN 105#define Mod 20007using namespace std;int n,m,k;int a[105],num[1005],vis[1005];vector<int> mp[1005];void dfs(int v){    for(unsigned int i=0;i<mp[v].size();++i)    {        int x=mp[v][i];        if(!vis[x])        {            vis[x]=1;            num[x]++;            dfs(x);        }    }}int main(){    int t;    scanf("%d",&t);    for(int cas=1; cas<=t; ++cas)    {        memset(num,0,sizeof(num));        scanf("%d%d%d",&k,&n,&m);        for(int i=0;i<=n;++i)            mp[i].clear();        for(int i=0;i<k;++i)            scanf("%d",&a[i]);        while(m--)        {            int u,v;            scanf("%d%d",&u,&v);            mp[u].push_back(v);        }        for(int i=0;i<k;++i)        {            memset(vis,0,sizeof(vis));            vis[a[i]]=1;            num[a[i]]++;            dfs(a[i]);        }        int ans=0;        for(int i=1;i<=n;++i)        {            if(num[i]==k)                ans++;        }        printf("Case %d: %d\n",cas,ans);    }    return 0;}
0 0
原创粉丝点击