zoukankan      html  css  js  c++  java
  • 奶牛野炊

      

    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: KN, and M 
    Lines 2.. K+1: Line i+1 contains a single integer (1.. N) which is the number of the pasture in which cowi is grazing. 
    Lines K+2.. MK+1: Each line contains two space-separated integers, respectively A and B (both 1.. Nand 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

    Hint

    The cows can meet in pastures 3 or 4.
     
    #include<cstdio>
    #include<vector>
    #define N 10001
    
    using namespace std;
    int k,n,m;
    int cow[N];
    int sum[N];
    int vis[N];
    vector<int> g[N];
    void dfs(int i)
    {
        vis[i]=1;//标记为已到达
        int len=g[i].size();//从当前牧场可到达其他牧场的个数
        for(int j=0;j<len;j++)//枚举所有可到达的牧场
        {
            int next=g[i][j];
            if(!vis[next])//如果下一个牧场未到达,继续向下搜索
                dfs(next);
        }
    }
    int main()
    {
        scanf("%d%d%d",&k,&n,&m);
        for(int i=1;i<=k;i++)
            scanf("%d",&cow[i]);
        while(m--)//vector邻接表建图
        {
            int x,y;
            scanf("%d%d",&x,&y);
            g[x].push_back(y);
        }
     
        for(int i=1;i<=k;i++)
        {
            dfs(cow[i]);//dfs每一头牛
            for(int j=1;j<=n;j++)//统计每一个牧场的到达数
            {
                sum[j]+=vis[j];
                vis[j]=0;
            }
        }
     
        int cnt=0;
        for(int i=1;i<=n;i++)//枚举所有牧场
            if(sum[i]==k)//如果该牧场所有牛均能到达
                cnt++;
     
        printf("%d
    ",cnt);
     
        return 0;
    }
    这个题用深搜写比较好,它的核心思想就是试图寻找奶牛能走过的牧场,然后进行标记,标记为一。然后将这些农场留下的vis数组里面的一足迹加起来,如果等于了K奶牛数,这就说明,所有的奶牛都来过,然后就说明这个牧场就是我们要找的牧场了。
    每次将vis的一加完以后,立刻赋值为零,表示没有来过,这时候就可以继续进入下一头牛的dfs了。
    所有的牛dfs之后,真个sum数组的眉目就清楚起来了,这时候答案也就出来了,要注意的是如果从零开始存储数据的话,要注意vis下标与传入形参的关系,记得减一哦。
  • 相关阅读:
    laravel5.6 调用第三方类库
    substring
    SpringSecurity3配置及原理简介
    正则表达式
    type=json
    正则表达式2
    笔记1
    oracle 自带函数大全及例子
    Vector容器类
    HQL
  • 原文地址:https://www.cnblogs.com/xyqxyq/p/9432650.html
Copyright © 2011-2022 走看看