[BZOJ1648]&&[Usaco2006 Dec]Cow Picnic 奶牛野餐

描述 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.

K(1≤K≤100) 只奶牛分散在 N(1≤N≤1000) 个牧场.现在她们要集中起来进餐.牧场之间有 M(1≤M≤10000) 条有向路连接,而且不存在起点和终点相同的有向路.她们进餐的地点必须是所有奶牛都可到达的地方.那么,有多少这样的牧场呢?

输入格式 InputFormat

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.

第 1 行输入 K,N,M. 接下来 K 行,每行一个整数表示一只奶牛所在的牧场编号.接下来 M 行,每行两个整数,表示一条有向路的起点和终点。

输出格式 OutputFormat

Line 1: The single integer that is the number of pastures that are reachable by all cows via the one-way paths.

所有奶牛都可到达的牧场个数。

样例输入 SampleInput

3 7 20
1
2
7
7 1
2 3
6 3
5 4
3 5
3 2
4 2
7 2
3 5
2 7
1 5
1 6
7 1
6 5
7 5
4 7
6 4
5 4
6 1
5 7

样例输出 SampleOutput

7

来源 Source

Silver


BZOJ 1648


代码 Code

从每头牛的点开始 bfs 访问到的点次数 + 1。动态数组貌似挺好用的。

#include <stdio.h>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <vector>
using namespace std;
int a[1005];
vector <int> c[1005];
int i,j,t,n,m,l,r,k,z,y,x,ans=0;
int f[1005];
bool b[1005];
inline int read()
{
    int x=0;char ch=getchar();
    while (ch<'0' || ch>'9') ch=getchar();
    while (ch>='0' && ch<='9') x=x*10+ch-'0',ch=getchar();
    return x;
}
void dfs(int s)
{
    int i,j,t,z,y,x;
    f[s]++;
    b[s]=true;
    if (f[s]==k) ans++;
    for (i=0;i<c[s].size();i++) if (b[c[s][i]]==false)
    {
        dfs(c[s][i]);
    }
}
int main()
{
    memset(f,0,sizeof(f));
    k=read();n=read();m=read();
    for (i=1;i<=k;i++) a[i]=read();
    for (i=1;i<=m;i++)
    {
        x=read();y=read();
        c[x].push_back(y);
    }
    for (i=1;i<=k;i++)
    {
        memset(b,0,sizeof(b));
        dfs(a[i]);
    }
    printf("%d\n",ans);
    return 0;
}