这道题之前做过,这次做一直有两个测试点不能通过,问题就在于他所给出的父子关系信息时是否按照顺序给出,答案是不是,所以不能在循环内部进行level的赋值。
ac代码:
#include <iostream>
#include <vector>
using namespace std;
struct node {
int level;
bool yes;
int father;
node() {
yes = true;
}
};
int main() {
int n, m;
cin >> n >> m;
vector<node> v1(n + 1);
v1[1].level = 1;
int res[101] = { 0 };
int maxLevel = 1;
for (int i = 0; i < m; i++) {
int a, num;
cin >> a >> num;
v1[a].yes = false;
for (int j = 0; j < num; j++) {
int temp;
cin >> temp;
v1[temp].father = a;
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (v1[j].father == i) {
v1[j].level = v1[i].level + 1;
}
}
}
for (int i = 1; i <= n; i++) {
if (v1[i].yes == true) {
res[v1[i].level]++;
}
if (v1[i].level > maxLevel)
maxLevel = v1[i].level;
}
for (int i = 1; i <= maxLevel; i++) {
if (i != 1)
cout << " ";
cout << res[i];
}
cout << endl;
}