Codeforces Round #387 (Div. 2) 747E

本文介绍了一种通过特定输入方式生成树形结构的方法,并利用非递归的方式进行树的构建,最后按照节点的深度顺序输出节点。文章还分享了使用getline的新技巧。

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

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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值