Happy Tree Friend!(递归模拟) - 拼多多2018提前批笔试-服务器端开发工程师

这里写图片描述
这里写图片描述

解题思路:vector+结构体 模拟,递归输出。调试了很久,注意|–(此处有空格)name,前面空格每4个一组。

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
const int Maxn = 1005;

typedef struct Node
{
    string name;
    vector<int> Vec;
};

Node node[Maxn];
string stringStruct;

bool cmp(const int& a, const int& b)
{
    return node[a].name<node[b].name;
}

void Print(int id, bool last)
{
    cout << node[id].name << endl;
    if(node[id].Vec.size()==0)
        return;
    sort(node[id].Vec.begin(), node[id].Vec.end(), cmp);
    if(id>0)
    {
        stringStruct+="|   ";
        if(last)
            stringStruct[stringStruct.length()-4] = ' ';
    }
    for(int i = 0; i < node[id].Vec.size(); ++i)
    {
        if(i==node[id].Vec.size()-1)
        {
            cout << stringStruct << "`-- ";
            Print(node[id].Vec[i], true);
        }
        else
        {
            cout << stringStruct << "|-- ";
            Print(node[id].Vec[i], false);
        }
    }
    if(id>0)
        stringStruct = stringStruct.substr(0, stringStruct.length()-4);
}

int main()
{
    int n, fa;
    string stringStruct;
    while(cin >> n)
    {
        for(int i = 0; i < n; ++i)
            node[i].Vec.clear();
        for(int i = 0; i < n; ++i)
        {
            cin >> node[i].name >> fa;
            node[fa].Vec.push_back(i);
        }
        Print(0, true);
    }
    return 0;
}
/*
10
my-app -1
src 0
main 1
java 2
resource 2
webapp 2
test 1
java 6
resource 6
pom.xml 0
*/
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值