当前位置:网站首页>信息学奥赛一本通 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;
}
边栏推荐
- 2022-07-04:以下go语言代码输出什么?A:true;B:false;C:编译错误。 package main import 'fmt' func
- Scala基础教程--16--泛型
- 【2022年江西省研究生数学建模】冰壶运动 思路分析及代码实现
- Scala基础教程--17--集合
- 资料下载 丨首届腾讯技术开放日课程精华!
- Scala基础教程--19--Actor
- Unity makes revolving door, sliding door, cabinet door drawer, click the effect of automatic door opening and closing, and automatically play the sound effect (with editor extension code)
- Nature microbiology | viral genomes in six deep-sea sediments that can infect Archaea asgardii
- 学习路之PHP--phpstudy创建项目时“hosts文件不存在或被阻止打开”
- Li Kou brush question diary /day5/2022.6.27
猜你喜欢
随机推荐
[cloud native] what is the "grid" of service grid?
Learning path PHP -- phpstudy "hosts file does not exist or is blocked from opening" when creating the project
How to open an account is safe,
Wireshark packet capturing TLS protocol bar displays version inconsistency
使用FTP
Unity 制作旋转门 推拉门 柜门 抽屉 点击自动开门效果 开关门自动播放音效 (附带编辑器扩展代码)
VMware Tools和open-vm-tools的安装与使用:解决虚拟机不全屏和无法传输文件的问题
[HCIA continuous update] network management and operation and maintenance
[211] go handles the detailed documents of Excel library
I always thought that excel and PPT could only be used for making statements until I saw this set of templates (attached)
【2022年江西省研究生数学建模】冰壶运动 思路分析及代码实现
TCP两次挥手,你见过吗?那四次握手呢?
1、 Introduction to C language
Scala basic tutorial -- 18 -- set (2)
Detailed explanation of the maturity classification of ITSS operation and maintenance capability | one article clarifies the ITSS certificate
如何提高开发质量
ESP32-C3入门教程 问题篇⑫——undefined reference to rom_temp_to_power, in function phy_get_romfunc_addr
【机器学习的数学基础】(一)线性代数(Linear Algebra)(上+)
2022 ByteDance daily practice experience (Tiktok)
What if the self incrementing ID of online MySQL is exhausted?