当前位置:网站首页>1021 deep root (25 points)
1021 deep root (25 points)
2022-06-29 10:14:00 【Momo 623】
- Use a random dot x Conduct dfs,dfs Record the distance in x Farthest point set
- Take a random point from the set , Conduct dfs, Get the farthest point set again
- The intersection of two sets + Is the farthest node
Liunuo :
The main idea of the topic : give n Nodes (1~n) Between n side , Ask if it can form a tree , If it cannot be constructed, the number of connected components it has is output , If it can form a tree , Output the height of the deepest tree , Root node of tree . If there are more than one , Output from small to large .
analysis : First, the depth first search determines how many connected components it has . If there are more than one , Then output Error: x components, If only one , Just two deep first searches , Start with a node dfs Keep the nodes with the highest height , Then start at any of these nodes dfs Get the nodes with the highest height , The union of these two sets of nodes is the result
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
#include <set>
using namespace std;
const int n = 1e5 + 10;
int N;
vector<int> v[n];
bool dp[n];
// set<int> ans;
set<int> ans;
vector<int> temp;
int maxt;
void dfs(int k, int l)
{
dp[k] = 1;
if (maxt < l)
{
maxt = l;
temp.clear();
temp.push_back(k);
}
if (maxt == l)
temp.push_back(k);
for (auto &e : v[k])
if (!dp[e])
dfs(e, l + 1);
}
int main()
{
cin >> N;
int x, y;
for (int i = 1; i < N; i++)
{
cin >> x >> y;
v[x].push_back(y);
v[y].push_back(x);
}
int cnt = 0;
for (int i = 1; i <= N; i++)
{
if (!dp[i])
{
cnt++;
dfs(i, 1);
if (i == 1)
for (auto &e : temp)
ans.insert(e);
}
}
if (cnt != 1)
printf("Error: %d components", cnt);
else
{
temp.clear();
maxt = 0;
memset(dp, 0, sizeof dp);
dfs(*ans.begin(), 1);
for (auto &e : temp)
ans.insert(e);
for (auto &e : ans)
cout << e << endl;
}
return 0;
}
边栏推荐
猜你喜欢
随机推荐
Sublime Text3 set to run your own makefile
GSOAP example - calc
Codeforces Round #659 (Div. 2)
Gmail: how to quickly read all messages
1021 Deepest Root (25 分)
Sixteen system counter and flow lamp
Minorgc, majorgc, fullgc
2019.10.20训练总结
Is flush stock trading software reliable and safe?
JNI.h说明
阿里云防火墙配置,多种设置方式(iptables和fireward)
container
函数指针、函数指针数组、计算器+转移表等归纳总结
Dsolve function of sympy
Container of the basic component of the flutter
HDU 4578 Transformation(线段树+有技巧的懒标记下放)
Application of keil5 integrated development environment for single chip microcomputer
蛇形填数
GridView of basic component of shutter
JVM之方法返回地址









