zoukankan      html  css  js  c++  java
  • 04.

    经典的dfs或者bfs。题目意思是让你输出一个家庭血统图中每一层中那些没有孩子的结点的数目。

    dfs解法:

    #include <iostream>
    #include <algorithm>
    using namespace std;
    
    int G[150][150],degree[101],depth=0,max_dep=0;
    int N,M;
    
    void dfs(int u)
    {
        int flag=0;
        if(depth>max_dep)max_dep=depth;
        for(int i=1;i<=N;i++)
        {
            if(G[u][i]==1)
            {
                flag=1;
                depth++;
                dfs(i);
                depth--;
            }
        }
        if(flag==0)degree[depth]++;
    }
    
    int main()
    {
        fill(G[0],G[0]+150*150,-1);
        fill(degree,degree+101,0);
        cin>>N>>M;
        for(int i=0;i<M;i++)
        {
            int v1,d,v2;
            cin>>v1>>d;
            for(int j=0;j<d;j++)
            {
                cin>>v2;
                G[v1][v2]=1;
            }
        }
        dfs(1);
        for(int i=0;i<=max_dep;i++)
        {
            if(i==0)
                cout<<degree[i];
            else
                cout<<' '<<degree[i];
        }
    }

    bfs解法。stl的queue也挺好用的,越来越喜欢stl了……

    #include <iostream>
    #include <algorithm>
    #include <vector>
    #include <queue>
    using namespace std;
    
    vector<int>G[101];
    //"degree" records the number of leaf nodes of each level
    //"level" records the depth of each node
    int degree[101],level[101],max_dep=-1;
    int N,M;
    
    void bfs()
    {
        queue<int>q;
        q.push(1);
        level[1]=0;
        while(!q.empty())
        {
            int u=q.front();
            max_dep=level[u]>max_dep?level[u]:max_dep;
            q.pop();
            if(G[u].size()==0)degree[level[u]]++;
            for(int i=0;i<G[u].size();i++)
            {
                int v=G[u][i];
                level[v]=level[u]+1;
                q.push(v);
            }
        }
    }
    
    int main()
    {
        fill(degree,degree+101,0);
        cin>>N>>M;
        for(int i=0;i<M;i++)
        {
            int v1,d,v2;
            cin>>v1>>d;
            for(int j=0;j<d;j++)
            {
                cin>>v2;
                G[v1].push_back(v2);
            }
        }
        bfs();
        for(int i=0;i<=max_dep;i++)
        {
            if(i==0)
                cout<<degree[i];
            else
                cout<<' '<<degree[i];
        }
    }
  • 相关阅读:
    golang 中 sync包的 WaitGroup
    Go_20: Golang 中 time 包的使用
    mysql 同步数据到 ElasticSearch 的方案
    mysql 对应 binlog 查看
    python3.6爬虫总结-01
    Golang 之协程详解
    golang私服搭建
    Ubuntu vim设置
    密码校验规则
    golang密码校验
  • 原文地址:https://www.cnblogs.com/KRCheung/p/6660223.html
Copyright © 2011-2022 走看看