1004 Counting Leaves (30分)

统计叶子结点数目

(BFS)

const int N=110;
vector<int> g[N];
int dep[N];
int cnt[N];
int maxh;
int n,m;

void bfs(int u)
{
    queue<int> q;
    q.push(u);
    dep[u]=1;

    while(q.size())
    {
        int t=q.front();
        q.pop();

        maxh=max(maxh,dep[t]);

        if(g[t].size() == 0)
        {
            int h=dep[t];
            cnt[h]++;
        }

        for(int i=0;i<g[t].size();i++)
        {
            int j=g[t][i];
            dep[j]=dep[t]+1;
            q.push(j);
        }
    }
}

int main()
{
    cin>>n>>m;

    while(m--)
    {
        int a,k;
        cin>>a>>k;

        for(int i=0;i<k;i++)
        {
            int b;
            cin>>b;
            g[a].pb(b);
        }
    }

    bfs(1);

    for(int i=1;i<=maxh;i++)
    {
        if(i == 1) cout<<cnt[i];
        else cout<<' '<<cnt[i];
    }

    //system("pause");
    return 0;
}

(DFS),简短

const int N=110;
vector<int> g[N];
int cnt[N];
int maxh;
int n,m;

void dfs(int u,int d)
{
    maxh=max(maxh,d);
    if(g[u].size() == 0)
    {
        cnt[d]++;
        return;
    }

    for(int i=0;i<g[u].size();i++)
    {
        int j=g[u][i];
        dfs(j,d+1);
    }
}

int main()
{
    cin>>n>>m;

    while(m--)
    {
        int a,k;
        cin>>a>>k;

        for(int i=0;i<k;i++)
        {
            int b;
            cin>>b;
            g[a].pb(b);
        }
    }

    dfs(1,1);

    for(int i=1;i<=maxh;i++)
    {
        if(i == 1) cout<<cnt[i];
        else cout<<' '<<cnt[i];
    }

    //system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/fxh0707/p/14225087.html