当前位置:网站首页>信息学奥赛一本通 1336:【例3-1】找树根和孩子
信息学奥赛一本通 1336:【例3-1】找树根和孩子
2022-07-04 17:14:00 【君义_noip】
【题目链接】
【题目考点】
1. 树 双亲表示法
设pa数组,pa[i]表示第i结点的双亲结点的编号。
【解题思路】
解法1:双亲表示法
用双亲表示法保存整棵树的信息,pa[i]表示第i结点的双亲结点的编号。遍历pa数组求出每个结点的度(树中结点的度就是该结点孩子的数量),得到度最大的结点的编号。然后遍历pa数组,输出该结点的孩子。
【题解代码】
解法1:双亲表示法
#include <bits/stdc++.h>
using namespace std;
int par[101], deg[101];//par[i]:表示结点i的双亲, deg[i]:表示结点i的度
int main()
{
int n, m, x, y, root, maxDeg = 0, maxNum = 1;//root:表示根结点编号,maxNum:度最高结点编号,maxDeg:表示度最高结点的度,即孩子对多的结点的孩子数
cin >> n >> m;
for(int i = 1; i <= m; ++i)
{
cin >> x >> y;
par[y] = x;//y的双亲是x
}
for(int i = 1; i <= n; ++i)
{
if(par[i] == 0)//双亲是0的结点是根结点
root = i;
deg[par[i]]++;//结点i的双亲的度加1
}
cout << root << endl;
for(int i = 1; i <= n; ++i)//查找度最大的结点
{
if(deg[i] > maxDeg)
{
maxDeg = deg[i];//最大度数
maxNum = i;//度数最大的顶点的编号
}
}
cout << maxNum << endl;
for(int i = 1; i <= n; ++i)//顺序遍历各个结点,看哪些结点是度最大结点的孩子
{
if(par[i] == maxNum)
cout << i << ' ';
}
return 0;
}
边栏推荐
- Scala basic tutorial -- 19 -- actor
- Imitation of numpy 2
- Is it safe to download the mobile version of Anxin securities and open an account online
- Grain Mall (I)
- 其他InterSystems %Net工具
- Torchdrug tutorial
- 字节跳动Dev Better技术沙龙成功举办,携手华泰分享Web研发效能提升经验
- 力扣刷题日记/day6/6.28
- Scala basic tutorial -- 13 -- advanced function
- MySQL common add, delete, modify and query operations (crud)
猜你喜欢

Reptile elementary learning

Load test practice of pingcode performance test

输入的查询SQL语句,是如何执行的?

Basic tutorial of scala -- 16 -- generics

I wrote a learning and practice tutorial for beginners!

Scala基础教程--15--递归

一直以为做报表只能用EXCEL和PPT,直到我看到了这套模板(附模板)

Learning path PHP -- phpstudy "hosts file does not exist or is blocked from opening" when creating the project

Microservice architecture debate between radical technologists vs Project conservatives

如何提高开发质量
随机推荐
[go language question brushing chapter] go conclusion chapter | introduction to functions, structures, interfaces, and errors
How to improve development quality
Scala basic tutorial -- 15 -- recursion
力扣刷题日记/day4/6.26
Scala基础教程--18--集合(二)
[cloud voice suggestion collection] cloud store renewal and upgrading: provide effective suggestions, win a large number of code beans, Huawei AI speaker 2!
Load test practice of pingcode performance test
android使用SQLiteOpenHelper闪退
Torchdrug tutorial
Improve the accuracy of 3D reconstruction of complex scenes | segmentation of UAV Remote Sensing Images Based on paddleseg
完善的js事件委托
力扣刷題日記/day6/6.28
My colleagues quietly told me that flying Book notification can still play like this
同事悄悄告诉我,飞书通知还能这样玩
[HCIA continuous update] network management and operation and maintenance
一直以为做报表只能用EXCEL和PPT,直到我看到了这套模板(附模板)
Detailed explanation of the maturity classification of ITSS operation and maintenance capability | one article clarifies the ITSS certificate
Uni app and uviewui realize the imitation of Xiaomi mall app (with source code)
【机器学习的数学基础】(一)线性代数(Linear Algebra)(上+)
蓝桥:合根植物