标签:
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
Output
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; }
标签:
原文地址:http://www.cnblogs.com/program-ccc/p/5628106.html