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.
輸入輸出樣例
輸入 #1
2 4 4 2 3 1 2 1 4 2 3 3 4輸出 #1
2說明/提示
The cows can meet in pastures 3 or 4.
思路:從奶牛所在牧場出發,dfs遍歷所有牧場,當牧場被遍歷的次數==奶牛數時,表明所有奶牛都可到達此牧場,滿足條件,ans++
代碼如下:
#include<bits/stdc++.h>
using namespace std;
bool vis[1010];
int bian[1010],a[1010];
int k,n,m,ans;
vector<int> G[1010];
void dfs(int x){
?? ?vis[x]=1;
?? ?bian[x]++;//此牧場被遍歷的次數
?? ?for(int i=0;i<G[x].size();i++){
?? ??? ?if(!vis[G[x][i]]){
?? ??? ??? ?dfs(G[x][i]);
?? ??? ?}
?? ?}
}
int main(){
?? ?cin>>k>>n>>m;
?? ?for(int i=1;i<=k;i++){
?? ??? ?cin>>a[i];//每頭奶牛所在牧場
?? ?}
?? ?for(int i=1;i<=m;i++){
?? ??? ?int x,y;
?? ??? ?cin>>x>>y;
?? ??? ?G[x].push_back(y);//建邊
?? ?}
?? ?for(int i=1;i<=k;i++){
?? ??? ?memset(vis,0,sizeof(vis)); //記住每次遍歷前都要先清0
?? ??? ?dfs(a[i]);
?? ?}
?? ?for(int i=1;i<=n;i++){
?? ??? ?if(bian[i]==k) ans++;//key!
?? ?}
?? ?cout<<ans<<endl;
?? ?return 0;
}
總結
以上是生活随笔為你收集整理的P2853 [USACO06DEC]Cow Picnic S的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【运维面试】面试官:你们的阿里云是怎么维
- 下一篇: 苹果悬浮球_买了一万块钱的苹果手机,悬浮