从零开始学习c++,参考了别人的代码,所以在写这道题之前先去学习了迭代器,vector,和map,大致思路就是先用一个map<a,vcetor[a]>来记录所有输入的父子关系,然后将其转化为一个vector,根据node中的level来排序,最后使用这个vector输出答案。
容器什么的真的好烧脑,第一次提交的时候报错了然后发现是因为把一个vector定义在循环外面,然后后来的循环中不能被全部覆盖。造成最后死循环。
测试用例:
10 4
01 3 02 03 04
02 1 05
03 2 06 07
04 3 08 09 10
正确输出:
0 0 6
#define MAX 1000;
#include<string>
#include<algorithm>
#include<vector>
#include<map>
#include<iostream>
using namespace std;
typedef struct {
string ID;
int level=MAX;
bool leaf=true;
}node;
map<string, vector<string>> relation;
vector<node> tree(101);
bool cmp(node a, node b) {
return a.level < b.level;//升序排序
}
void buildTree(string ID) {
auto iter = relation.find(ID);//找到说明是父节点
tree[stoi(ID)].ID = ID ;
if (iter != relation.end()) {
tree[stoi(ID)].leaf = false;
for (int i = 0; i < iter->second.size(); i++) {//标记每个子节点的level
tree[stoi(iter->second.at(i))].level = tree[stoi(ID)].level + 1;
buildTree(iter->second.at(i));
}
}
}
int main(){
int n,m,k;
cin >> n>>m;
for (int i = 0; i < m; i++) {
string parent, tmp; vector<string> child;
cin >> parent>>k;
for (int j = 0; j < k; j++) {
cin >> tmp;
child.push_back(tmp);
}
relation[parent] = child;//建立关系映射
}
tree[1].level = 1;
buildTree("01");//从根节点开始递归将每个node放入容器,并计算每个node的level
sort(tree.begin(), tree.end(), cmp);
int max_level = tree[n - 1].level;
for (int i = 1; i <= max_level; i++) {
int count = 0;
for (int j = 0; j < n; j++) {
if (tree[j].level == i && tree[j].leaf)
count++;
}
if (i == 1) cout << count;
else cout << ' ' << count;
}
return 0;
}