列表

详情


NC25098. [USACO 2006 Dec S]Cow Picnic

描述

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.

输入描述

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

输出:

2

说明:

4<--3
^ ^
| |
| |
1-->2
The pastures are laid out as shown above, with cows in pastures 2 and 3.
The cows can meet in pastures 3 or 4.

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++14(g++5.4) 解法, 执行用时: 11ms, 内存消耗: 492K, 提交时间: 2019-06-25 15:23:27

#include <bits/stdc++.h>
using namespace std;
vector<int>G[1005];
bool vis[1005];
int k,n,m;
int pos[105];
int cnt[1005];

void dfs(int x){
	cnt[x]++;
	for(int i=0;i<G[x].size();++i){
		int v = G[x][i];
		if(!vis[v]){
			vis[v] = 1;
			dfs(v);
		}
	}
}
int main(){
	scanf("%d%d%d",&k,&n,&m);

	for(int i=1;i<=k;++i) scanf("%d",&pos[i]);

	int x,y;
	for(int i=1;i<=m;++i){
		scanf("%d%d",&x,&y);
		G[x].push_back(y);
	}
	for(int i=1;i<=k;++i){
		memset(vis,0,sizeof(vis));
		vis[pos[i]] = 1;
		dfs(pos[i]);
	}
	int ans = 0;
	for(int i=1;i<=n;++i){
		if(cnt[i]>=k) ans++;
	}
	printf("%d\n",ans);
	return 0;
}

C++11(clang++ 3.9) 解法, 执行用时: 115ms, 内存消耗: 1628K, 提交时间: 2019-07-03 20:30:40

#include<bits/stdc++.h>
using namespace std;
bool f[1010][1010],dp[110][1010],dp2[1010];
int n,m,k,a[110];
void dfs(int i,int x){
	dp[i][x]=true;
	for(int j=1;j<=n;j++)
	if(f[x][j]&&!dp[i][j])dfs(i,j);
} 
int main(){
	cin>>k>>n>>m;
	for(int i=1;i<=k;i++)
	cin>>a[i];
	for(int i=1;i<=m;i++){
		int a,b;
		cin>>a>>b;
		f[a][b]=true;
	}
	for(int i=1;i<=k;i++)
	dfs(i,a[i]);
	for(int i=1;i<=k;i++)
	for(int j=1;j<=n;j++)
	if(!dp[i][j])dp2[j]=true;
	int ans=0;
	for(int i=1;i<=n;i++)
	if(!dp2[i])ans++;
	cout<<ans<<"\n";
	return 0;
}

上一题