Lightoj1111——Best Picnic Ever(dfs)

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 20007
using 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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章