当前位置:网站首页>Binary tree topic -- Luogu p3884 [jloi2009] binary tree problem (DFS for binary tree depth BFS for binary tree width Dijkstra for shortest path)
Binary tree topic -- Luogu p3884 [jloi2009] binary tree problem (DFS for binary tree depth BFS for binary tree width Dijkstra for shortest path)
2022-07-02 10:59:00 【Morgannr】
[JLOI2009] Binary tree problem
Title Description
The depth of a binary tree as shown in the figure below 、 The width and the distance between nodes are :
- depth : 4 4 4
- Width : 4 4 4
- node 8 and 6 Distance between : 8 8 8
- node 7 and 6 Distance between : 3 3 3
Where width represents the maximum number of nodes in the same layer on the binary tree .

Give one to 1 Binary tree with node No. as root , Request its depth 、 Width and two specified nodes x , y x, y x,y Distance between .
Input format
The first line is an integer , Represents the number of nodes in a tree n n n.
Next n − 1 n - 1 n−1 That's ok , Two integers per line u , v u, v u,v, Indicates that there is a connection on the tree u , v u, v u,v The edge of .
The last line has two integers x , y x, y x,y, Express and seek x , y x, y x,y Distance between .
Output format
Enter three lines , One integer per row , Represent the depth of the binary tree in turn 、 Width and x , y x, y x,y Distance between .
Examples #1
The sample input #1
10
1 2
1 3
2 4
2 5
3 6
3 7
5 8
5 9
6 10
8 6
Sample output #1
4
4
8
Tips
For all test points , Guarantee 1 ≤ u , v , x , y ≤ n ≤ 100 1 \leq u, v, x, y \leq n \leq 100 1≤u,v,x,y≤n≤100, And what is given is a tree .
The question :
Give me a With 1 Binary tree with node No. as root , Request its depth 、 Width and two specified nodes x, y Distance between .
Ideas :
The depth of binary tree is easy to find , direct dfs solve that will do .
about The width of the binary tree , Here is a good idea :
In the process of wide search , We can Add a... To the queue “0” Mark , As The distinction between extended layers in wide search , It's also The sign of the end of this layer ( The end of the first floor ).
Let's take an example , Let's suppose that's the case A binary tree :
At first we were first floor After the root node Add one “0” Mark ( The first layer has only roots ), about The second floor , When traversal to First floor “0” when , Directly in The second floor Ending Expand into a “0” Mark that will do .
Same thing , When traversing to the second layer “0” when , Directly on the third floor Ending Expand into a “0” Mark .
Get the team leader every time when , If The header value is 0, Then we Judge the number of nodes in the current layer , and Update Max ans.
Final ans That is, the width of the binary tree .
The code snippet is as follows :
int bfs(int u) // Width The return value is the width of the binary tree
{
int ans = 0;
vector<int> level; // Use an auxiliary vector level To store all nodes of a certain layer , Its size is used as the width of the updated binary tree ans The basis of
queue<int> q; q.push(u), q.push(0); // At first, the root node and “0” Mark Push into the queue
while (q.size())
{
auto t = q.front(); q.pop();
if (!t) // If t yes “0” Mark , It means that at the end of a certain floor
{
if (level.empty()) break; // If the current number of stratification points is 0, It indicates that all nodes of the binary tree have been traversed , End the traversal directly
ans = max(ans, (int)level.size()); // Otherwise update the answer ( Width of binary tree )
q.push(0); // Expand one at the end of the next layer “0” Mark
level.clear(); // Clear the current layer , Ready to save the next layer
continue;
}
level.push_back(t); // First add the current point
if (l[t]) q.push(l[t]); // Add left son
if (r[t]) q.push(r[t]); // Add your son
}
return ans;
}
Find the distance between two nodes in a given tree , Let's use it directly here Adjacency table to store graph , After use simple dijkstra Solve the shortest path that will do .
Be careful :
- In the subject , From the binary tree The weight of each edge is
1, The weight of each edge from bottom to top is2, It seems that there is no mention of .
Code :
#define _CRT_SECURE_NO_WARNINGS 1
#include <bits/stdc++.h>
using namespace std;
//#define int long long
//#define map unordered_map
const int N = 110, M = (N << 1), inf = 0x3f3f3f3f;
map<int, int> l, r;
int n;
int depth = -1;
int g[N][N];
int dist[N];
bool st[N];
void dfs1(int u, int dep)// depth
{
if (!l[u] && !r[u])
{
depth = max(depth, dep);
return;
}
if (l[u]) dfs1(l[u], dep + 1);
if (r[u]) dfs1(r[u], dep + 1);
}
int bfs(int u) // Width Because this problem does not require the output of nodes of a certain layer , So we are directly the same int width Record the number of nodes in the current layer , And use width to update ans
{
int ans = 0;
int width = 0; // There is no need for vector 了 , It's too much trouble
queue<int> q; q.push(u), q.push(0);
while (q.size())
{
auto t = q.front(); q.pop();
if (!t)
{
if (!width) break;
ans = max(ans, width);
q.push(0);
width = 0;
continue;
}
width++;
if (l[t]) q.push(l[t]);
if (r[t]) q.push(r[t]);
}
return ans;
}
int dijk(int a, int b)
{
memset(dist, 0x3f, sizeof dist);
memset(st, false, sizeof st);
dist[a] = 0;
for (int i = 0; i < n; ++i)
{
int t = -1;
for (int j = 1; j <= n; ++j)
{
if (!st[j] && (t == -1 || dist[t] > dist[j])) t = j;
}
st[t] = true;
for (int j = 1; j <= n; ++j)
{
dist[j] = min(dist[j], dist[t] + g[t][j]);
}
}
return dist[b];
}
signed main()
{
int T = 1; //cin >> T;
while (T--)
{
memset(g, 0x3f, sizeof g);
cin >> n;
for (int i = 0; i < n - 1; ++i)
{
int x, y; cin >> x >> y;
if (!l[x]) l[x] = y;
else if (!r[x]) r[x] = y;
g[x][y] = min(g[x][y], 1);
g[y][x] = min(g[y][x], 2);
}
dfs1(1, 1);
cout << depth << '\n';
cout << bfs(1) << '\n';
int a, b; cin >> a >> b;
cout << dijk(a, b) << '\n';
}
return 0;
}
边栏推荐
- static 函数中的静态变量
- PCL extracts a subset from a point cloud
- JSP webshell免殺——JSP的基礎
- 6种单例模式的实现方式
- 洛谷 P3398 仓鼠找 sugar(树上倍增 lca 判断树中两条路径是否相交 结论)
- 1287_ Implementation analysis of prvtaskistasksuspended() interface in FreeRTOS
- 【付费推广】常见问题合集,推荐榜单FAQ
- Start class, data analysis, high salary training plan, elite class
- PCL 从一个点云中提取一个子集
- MySQL lethal serial question 4 -- are you familiar with MySQL logs?
猜你喜欢
![[TS] 1368 seconds understand typescript generic tool types!](/img/2b/58a850b52ce8a9b2e6e7b6b72b0fe5.jpg)
[TS] 1368 seconds understand typescript generic tool types!

Leetcode+ 76 - 80 storm search topic

Matlab processing of distance measurement of experimental electron microscope

全网显示 IP 归属地,是怎么实现的?

(五)APA场景搭建之挡位控制设置

MYSQL环境配置

axis设备的rtsp setup头中的url不能带参

Dialogue Wu Gang: why do I believe in the rise of "big country brands"?
![[SUCTF2018]followme](/img/63/9104f9c8bd24937b0fc65053efec96.png)
[SUCTF2018]followme

4. Random variables
随机推荐
14. Code implementation of semaphore
AppGallery Connect场景化开发实战—图片存储分享
PCL 点云转深度图像
13. Semaphore critical zone protection
使用sqlcipher打开加密的sqlite方法
4. Random variables
Read H264 parameters from mediarecord recording
Nodejs+express+mysql simple blog building
Record attributeerror: 'nonetype' object has no attribute 'nextcall‘
MySQL lethal serial question 3 -- are you familiar with MySQL locks?
Easyexcel, a concise, fast and memory saving excel processing tool
计算序列之和
HDU1234 开门人和关门人(水题)
axis设备的rtsp setup头中的url不能带参
618 what is the secret of dominating the list again? Nike's latest financial report gives the answer
The URL in the RTSP setup header of the axis device cannot take a parameter
转换YV12到RGB565图像转换,附YUV转RGB测试
Start class, data analysis, high salary training plan, elite class
Hdu1228 a + B (map mapping)
【TS】1368- 秒懂 TypeScript 泛型工具类型!