今日题目:cow
题目描述
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.
题目分析
题目难度:⭐️
题目涉及算法:dfs,队列。
ps:有能力的小伙伴可以尝试优化自己的代码或者一题多解,这样能综合提升自己的算法能力
题解报告:
1.思路
这题我选择的dfs,搜牧场不行 70%,因为有向图换了一下方向 让牛找牧场 就过了
2.代码
#include <bits/stdc++.h> using namespace std; const int N = 1011; int k,n,m,c,sum; int a[N][N],b[N],arr[N][N]; int dfs(int p) { for(int i=1;i<=n;i++) { if(arr[c][i]==0&&a[p][i]) { arr[c][i]=1; dfs(i); } } } int main() { cin>>k>>n>>m; if(k==1) { cin>>c; cout<<c; return 0; } for(int i=1;i<=k;i++) { int xx; cin>>xx; b[xx]=1; } for(int i=1;i<=m;i++) { int p1,p2; cin>>p1>>p2; a[p1][p2]=1; } for(int i=1;i<=n;i++) { if(b[i]==1) { c=i; arr[i][i]=1; dfs(i); } } for(int i=1;i<=n;i++) { int sum=1; for(int j=1;j<=n;j++) { if(arr[j][i]==0&&b[j]) { sum=0; } } if(sum==1) { sum++; } } cout<<sum; return 0; }