P2853 [USACO06DEC]Cow Picnic S
作者:互联网
P2853 [USACO06DEC]Cow Picnic S
题目描述
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: K, N, 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.
输出格式
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
说明/提示
The cows can meet in pastures 3 or 4.
思路
因为需要找到k头奶牛能到的地方,对cow[i]进行DFS,存储每个点nc[i]有多少头奶牛能到,最后遍历一下,找出nc[i]=k的个数即可
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int k,n,m;//k头牛,n个农场,
int v[10005][10005];//记录路径
int nc[1005];//每个农场可到达的次数
int cow[1005];//每头牛在哪个农场
int vis[1005];//记录某个农场是否遍历过
int x,y;
int ans;//最终的答案
void dfs(int m){//遍历每头牛为起点的位置
vis[m]=1;//将这个位置设置为已走过
nc[m]++;//这个位置的农场走过的次数+1
for(int i=1;i<=n;i++){//继续遍历从该农场的位置向其他农场的位置走
if(!vis[i]&&v[m][i]){//如果i位置的农场未被走过,且有通路
dfs(i);//向下遍历该农场的位置
}
}
}
int main(){
cin>>k>>n>>m;
for(int i=1;i<=k;i++) cin>>cow[i];//记录每头牛的位置
for(int i=1;i<=m;i++){
cin>>x>>y;
v[x][y]=1;
}
for(int i=1;i<=k;i++){//以每头牛为起点进行遍历
memset(vis,0,sizeof(vis));//每次都要重置,将所有位置的农场都设为未走过
dfs(cow[i]);
}
for(int i=1;i<=n;i++){
if(nc[i]==k) ans++;//如果这个农场被走过的次数==牛的总数,那么这个农场符合条件
}
cout<<ans;
return 0;
}
标签:pastures,遍历,Picnic,USACO06DEC,int,农场,cows,pasture,P2853 来源: https://blog.csdn.net/weixin_52834435/article/details/122666052