当前位置:网站首页>信息学奥赛一本通 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;
}
边栏推荐
- Li Kou brush question diary /day6/6.28
- Nature microbiology | viral genomes in six deep-sea sediments that can infect Archaea asgardii
- Lua EmmyLua 注解详解
- Scala基础教程--13--函数进阶
- 力扣刷题日记/day1/2022.6.23
- Unity 制作旋转门 推拉门 柜门 抽屉 点击自动开门效果 开关门自动播放音效 (附带编辑器扩展代码)
- [2022 Jiangxi graduate mathematical modeling] curling movement idea analysis and code implementation
- [cloud voice suggestion collection] cloud store renewal and upgrading: provide effective suggestions, win a large number of code beans, Huawei AI speaker 2!
- 基于unity的愤怒的小鸟设计
- [go ~ 0 to 1] read, write and create files on the sixth day
猜你喜欢
输入的查询SQL语句,是如何执行的?
力扣刷题日记/day4/6.26
VMware Tools和open-vm-tools的安装与使用:解决虚拟机不全屏和无法传输文件的问题
线上MySQL的自增id用尽怎么办?
Halcon模板匹配
基于unity的愤怒的小鸟设计
Behind the ultra clear image quality of NBA Live Broadcast: an in-depth interpretation of Alibaba cloud video cloud "narrowband HD 2.0" technology
2022年字节跳动日常实习面经(抖音)
Mxnet implementation of googlenet (parallel connection network)
Scala基础教程--18--集合(二)
随机推荐
工厂从自动化到数字孪生,图扑能干什么?
[system disk back to U disk] record the operation of system disk back to U disk
File processing examples of fopen, FREAD, fwrite, fseek
Just today, four experts from HSBC gathered to discuss the problems of bank core system transformation, migration and reconstruction
完善的js事件委托
An example of multi module collaboration based on NCF
[210] usage of PHP delimiter
线上MySQL的自增id用尽怎么办?
.NET ORM框架HiSql实战-第二章-使用Hisql实现菜单管理(增删改查)
Li Kou brush question diary /day7/2022.6.29
力扣刷题日记/day7/6.30
Scala basic tutorial -- 20 -- akka
2022年字节跳动日常实习面经(抖音)
MySQL common add, delete, modify and query operations (crud)
What types of Thawte wildcard SSL certificates provide
[go ~ 0 to 1] read, write and create files on the sixth day
Installation and use of VMware Tools and open VM tools: solve the problems of incomplete screen and unable to transfer files of virtual machines
I always thought that excel and PPT could only be used for making statements until I saw this set of templates (attached)
Grain Mall (I)
一、C语言入门基础