
具體的思路就是每個節點存盤孩子數、id、和層號。輸入一次根據父母給孩子層號給父母孩子數。
最后統計所有節點,孩子數為0的層數的葉子節點+1.
#include <iostream>
#define MAX 100
using namespace std;
struct tree{
int ID;
int child_num;
int f;
};
int main()
{
tree test[MAX];
int N, M;
int n = 1;//已賦值的個數
int num[MAX] = { 0 };//每層的葉節點個數
int floa = 1;//層數
cin >> N;
cin >> M;
if (N == 1)
{
cout<<1;
return 0;
}
test->ID = 1;
test->child_num = 0;
test->f = 1;
for (int i = 1 ;i < N; i++)
{
test[i].ID = 0;
test[i].child_num = 0;
test[i].f = 0;
}
for (int i = 0; i < M; i++)
{
int ID,k,id[MAX];
cin >> ID;
cin >> k;
for (int j = 0; j < k; j++)
cin >> id[j];
int j = 0;
for(j=0;j<N;j++)
{
if(test[j].ID==ID)
break;
}
j++;
test[j - 1].child_num = k;
if (test[j - 1].f + 1 > floa)
floa = test[j - 1].f + 1;
for (int a = 0; a < k; a++)
{
if(a+n>=N)
return 1;
test[a + n].ID = id[a];
test[a + n].f = test[j - 1].f + 1;
}
n += k;
}
for (int i = 0; i < n; i++)
{
if (test[i].child_num == 0)
num[test[i].f-1]++;
}
for (int i = 0; i < floa; i++)
{
cout << num[i];
if (i != floa - 1)
cout << ' ';
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/134400.html
標籤:C++ 語言
上一篇:求大佬求解,為什么這一段沒有代碼
