Cow Picnic
Time Limit: 2000MS
Memory Limit: 65536K
Total Submissions: 5432
Accepted: 2243
Description
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.
Input
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.
Output
Line 1: The single integer that is the number of pastures that are reachable by all cows via the one-way paths.
Sample Input
2 4 4
2
3
1 2
1 4
2 3
3 4
Sample Output
2
思路:直接dfs遍历.
#include
#include
using namespace std;
const int MAXN=;
bool mp[MAXN][MAXN];
int belong[MAXN];//记录每个cow所属的pasture
int gather[MAXN];//记录每个pasture所能聚集的cow的个数
int vis[MAXN];
int k,n,m;
void dfs(int u)
{
vis[u]=;
gather[u]++;
for(int i=;i<=n;i++)
{
if(mp[u][i]&&!vis[i])//存在环
{
dfs(i);
}
}
}
int main()
{
while(scanf("%d%d%d",&k,&n,&m)!=EOF)
{
memset(mp,false,sizeof(mp));
memset(belong,,sizeof(belong));
memset(gather,,sizeof(gather));
memset(vis,,sizeof(vis));
for(int i=;i<=k;i++)
{
int x;
scanf("%d",&x);
belong[i]=x;
}
for(int i=;i<m;i++)
{
int u,v;
scanf("%d%d",&u,&v);
mp[u][v]=true;
}
for(int i=;i<=k;i++)
{
memset(vis,,sizeof(vis));
dfs(belong[i]);
}
int res=;
for(int i=;i<=n;i++)
if(gather[i]==k) //pasture聚集的row数目为k则res+1
res++;
printf("%d\n",res);
}
return ;
}
Java:
import java.util.*;
public class Main{
static Scanner cin = new Scanner(System.in);
static final int MAXN=1005;
static int k,n,m;
static int[] load=new int[105];
static ArrayList
static int[] mark=new int[MAXN];
static boolean[] vis=new boolean[MAXN];
static void dfs(int u)
{
mark[u]++;
vis[u]=true;
for(int i=0;i<arc[u].size();i++)
{
int to=arc[u].get(i);
if(!vis[to])
{
dfs(to);
}
}
}
public static void main(String[] args){
while(cin.hasNext())
{
Arrays.fill(load, 0);
Arrays.fill(mark, 0);
k=cin.nextInt();
n=cin.nextInt();
m=cin.nextInt();
for(int i=1;i<=n;i++)
{
arc\[i\]=new ArrayList<Integer>();
}
for(int i=1;i<=k;i++)
{
int pasture=cin.nextInt();
load\[i\]=pasture;
}
for(int i=0;i<m;i++)
{
int u,v;
u=cin.nextInt();
v=cin.nextInt();
arc\[u\].add(v);
}
for(int i=1;i<=k;i++)
{
if(load\[i\]!=0)
{
Arrays.fill(vis, false);
dfs(load\[i\]);
}
}
int res=0;
for(int i=1;i<=n;i++)
{
if(mark\[i\]==k)
res++;
}
System.out.println(res);
}
}
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章