P2853 [USACO06DEC]Cow Picnic S
作者:互联网
思路:反向建边,以每一个农场为起点dfs一遍,得到从这个农场开始能够访问到的奶牛数目cnt,若cnt = k说明所有的奶牛都能到这个农场,结果+1.
复杂度:\(O(n(n+n+m))=O(nm)\),1e7不会超时
#include<iostream>
#include<cstring>
using namespace std;
const int N = 1010, M = 10010;
int h[N], e[M], ne[M], idx;
int w[N], cnt;
int n, m, k;
int st[N];
void add(int a, int b){
e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}
void dfs(int u){
st[u] = 1;
cnt += w[u];
for(int i = h[u]; i != -1; i = ne[i]){
int j = e[i];
if(st[j] == 0) dfs(j);
}
}
int main(){
memset(h, -1, sizeof h);
cin >> k >> n >> m;
for(int i = 0; i < k; i ++){
int num;
cin >> num;
w[num] ++;
}
while(m --){
int a, b;
cin >> a >> b;
add(b, a);
}
int res = 0;
for(int i = 1; i <= n; i ++){
memset(st, 0, sizeof st);
cnt = 0;
dfs(i);
if(cnt == k) res ++;
}
cout << res << endl;
return 0;
}
标签:cnt,Picnic,USACO06DEC,idx,int,ne,dfs,num,P2853 来源: https://www.cnblogs.com/tomori/p/14314919.html