Cow Picnic -dfs

【题目】

The cows are having a picnic! Each of Farmer John's K (1 ≤ K ≤ 100) cows is grazing in one of N (1 ≤ N ≤ 1,000) pastures, conveniently numbered 1...N. The pastures are connected by M (1 ≤ M ≤ 10,000) one-way paths (no path connects a pasture to itself).

The cows want to gather in the same pasture for their picnic, but (because of the one-way paths) some cows may only be able to get to some pastures. Help the cows out by figuring out how many pastures are reachable by all cows, and hence are possible picnic locations.

K(1≤K≤100)只奶牛分散在N(1≤N≤1000)个牧场.现在她们要集中起来进餐.牧场之间有M(1≤M≤10000)条有向路连接,而且不存在起点和终点相同的有向路.她们进餐的地点必须是所有奶牛都可到达的地方.那么,有多少这样的牧场呢?

【输入】

Line 1: Three space-separated integers, respectively: <i>K</i>, <i>N</i>, and <i>M</i> <br>Lines 2..<i>K</i>+1: Line <i>i</i>+1 contains a single integer (1..<i>N</i>) which is the number of the pasture in which cow <i>i</i> is grazing. <br>Lines <i>K</i>+2..<i>M</i>+<i>K</i>+1: Each line contains two space-separated integers, respectively <i>A</i> and <i>B</i> (both 1..<i>N</i> and <i>A</i> != <i>B</i>), representing a one-way path from pasture <i>A</i> to pasture <i>B</i>.

【输出】

Line 1: The single integer that is the number of pastures that are reachable by all cows via the one-way paths.

【样例】

输入:

2 4 4
2
3
1 2
1 4
2 3
3 4

输出:

2

思路:从k个奶牛分别dfs,用mk[i]表示第i个牧场被遍历过多少次,最后只有mk[i]==k的牧场满足条件。无权的有向图用vector存储。

代码:

#include<iostream>
#include<vector>
#include<cstdio>
using namespace std;

int a[1001],mk[1001];
vector<int>b[1001];
int k,n,m;
int vis[1001];

void dfs(int x)
{
    vis[x]=1;
    mk[x]++;
    for(int i=0;i<b[x].size();i++)
        if(!vis[b[x][i]])
            dfs(b[x][i]);
}

int main()
{
    int x,y;
    cin>>k>>n>>m;
    for(int i=1;i<=k;i++)
        cin>>a[i];
    for(int i=1;i<=m;i++)
    {
        cin>>x>>y;
        b[x].push_back(y);
    }
    for(int i=1;i<=k;i++)
    {
        for(int j=1;j<=n;j++) vis[j]=0;
        dfs(a[i]);
    }
    int ans=0;
    for(int i=1;i<=n;i++)
        if(mk[i]==k)  ans++;
    cout<<ans<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/wentong_xu/article/details/81226465
dfs