Codeforces Round #387 (Div. 2) 747E

这题本身是个水题,但是写了半天

题意就是给出一个树的生成方式,让你还原这棵树,然后按深度输出结点

这个还原过程还是比较有趣的(没有用递归)

PS:getline的新姿势get

#include <iostream>
#include <vector>
#include <queue>
#include <cstdio>
using namespace std;
const int maxn = 1e6;
int deep[maxn], c[maxn], f[maxn];
string str[maxn];
string tmp;
vector <int> G[maxn];
queue <int> Q;
int main()
{
    int fa = 0, tot = 0, d = 0;
    while(getline(cin, str[++tot], ','))
    {
        getline(cin, tmp, ',');
        for(int i = 0; i < tmp.length(); i++) c[tot] = c[tot]*10 + tmp[i] - '0';
        f[tot] = fa; c[fa]--;
        deep[tot] = deep[fa] + 1;
        if(c[tot] != 0) { fa = tot; }
        while(c[fa] == 0) fa = f[fa];
    }
    tot--;
    for(int i = 1; i <= tot; i++) d = max(d, deep[i]);
    for(int i = 1; i <= tot; i++)
        G[f[i]].push_back(i);
    cout<<d<<endl;
    Q.push(0);
    while(!Q.empty())
    {
        int N = Q.size();
        for(int i = 0; i < N; i++)
        {
            int x = Q.front(); Q.pop();
            for(int j = 0; j < G[x].size(); j++)
            {
                int to = G[x][j];
                cout<<str[to]<<" ";
                Q.push(to);
            }
        }
        cout<<endl;
    }
}
原文地址:https://www.cnblogs.com/Saurus/p/6197367.html