码迷,mamicode.com
首页 > 其他好文 > 详细

POJ3256:Cow Picnic

时间:2016-06-29 20:31:44      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

Cow Picnic
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 5432   Accepted: 2243

Description

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..M+K+1: Each line contains two space-separated integers, respectively A and B (both 1..N and A != B), representing a one-way path from pasture A to pasture B.

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 4
2
3
1 2
1 4
2 3
3 4

Sample Output

2
思路:直接dfs遍历.
#include <cstdio>
#include <cstring>
using namespace std;
const int MAXN=1005;
bool mp[MAXN][MAXN];
int belong[MAXN];//记录每个cow所属的pasture 
int gather[MAXN];//记录每个pasture所能聚集的cow的个数 
int vis[MAXN];
int k,n,m;
void dfs(int u)
{
    vis[u]=1;
    gather[u]++;
    for(int i=1;i<=n;i++)
    {
        if(mp[u][i]&&!vis[i])//存在环 
        {
            dfs(i);
        }
    }
}
int main()
{
    while(scanf("%d%d%d",&k,&n,&m)!=EOF)
    {
        memset(mp,false,sizeof(mp));
        memset(belong,0,sizeof(belong));
        memset(gather,0,sizeof(gather));
        memset(vis,0,sizeof(vis));
        for(int i=1;i<=k;i++)
        {
            int x;
            scanf("%d",&x);
            belong[i]=x;
        }
        for(int i=0;i<m;i++)
        {
            int u,v;
            scanf("%d%d",&u,&v);
            mp[u][v]=true;
        }
        for(int i=1;i<=k;i++)
        {
            memset(vis,0,sizeof(vis));
            dfs(belong[i]);        
        }
        int res=0;
        for(int i=1;i<=n;i++)
            if(gather[i]==k)    //pasture聚集的row数目为k则res+1 
                res++;
        printf("%d\n",res);
    }
    return 0;
}

 

POJ3256:Cow Picnic

标签:

原文地址:http://www.cnblogs.com/program-ccc/p/5628106.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!