POJ

来源:互联网 发布:截动态图软件 编辑:程序博客网 时间:2024/05/29 08:37

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.

Input
Line 1: Three space-separated integers, respectively: KN, and M 
Lines 2.. K+1: Line i+1 contains a single integer (1.. N) which is the number of the pasture in which cow i is grazing. 
Lines K+2.. MK+1: Each line contains two space-separated integers, respectively Aand B (both 1.. N and A != B), representing a one-way path from pasture A to pastureB.
Output
Line 1: The single integer that is the number of pastures that are reachable by all cows via the one-way paths.
Sample Input
2 4 4231 21 42 33 4
Sample Output
2
Hint
The cows can meet in pastures 3 or 4.

题意:给出k头牛,n个牧场,m条牧场间的单向路径,每头牛都被分配到一个牧场,让求所有牛都能到达的牧场

ans[i]记录每个牧场有几头牛能到达,对于每头牛从他所在牧场出发搜索,到达某个牧场则该牧场的ans[i]++,最终ans[i]等于总牛数k的牧场即是所有牛都能到达的牧场。

代码:

#include<iostream>#include<string>#include<cstdio>#include<algorithm>#include<cmath>#include<iomanip>#include<queue>#include<cstring>#include<map>using namespace std;typedef long long ll;#define M 10005int k,n,m;int cow[105]; //每个牛在哪个牧场int ans[1005]; //每个牧场有几头牛能到达bool vis[1005]; //fs记录每头牛时,记录次牛到达过的点vector<int>mp[M]; //二维数组记录路径void dfs(int s){    ans[s]++;    vis[s]=true;    int i,len;    len=mp[s].size();    for(i=0;i<len;i++)    {        if(!vis[mp[s][i]])            dfs(mp[s][i]);    }}int main(){    int i,s,e;    scanf("%d%d%d",&k,&n,&m);    for(i=1;i<=k;i++)        scanf("%d",&cow[i]);    for(i=1;i<=m;i++)    {        scanf("%d%d",&s,&e);        mp[s].push_back(e);    }    //memset(ans,0,sizeof(ans));    for(i=1;i<=k;i++)    {        memset(vis,0,sizeof(vis));        dfs(cow[i]);    }    int cnt=0;    for(i=1;i<=n;i++)    {        if(ans[i]==k)            cnt++;    }    printf("%d\n",cnt);    return 0;}


原创粉丝点击