PAT菜鸡笔记1021 Deepest Root

1021 Deepest Root

A graph which is connected and acyclic can be considered a tree. The height of the tree depends on the selected root. Now you are supposed to find the root that results in a highest tree. Such a root is called the deepest root.

Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (≤10^​4) which is the number of nodes, and hence the nodes are numbered from 1 to N. Then N−1 lines follow, each describes an edge by given the two adjacent nodes’ numbers.

Output Specification:
For each test case, print each of the deepest roots in a line. If such a root is not unique, print them in increasing order of their numbers. In case that the given graph is not a tree, print Error: K components where K is the number of connected components in the graph.
在这里插入图片描述
在图中找构造出最长树的根结点,若不止一个连通分量则输出连通分量个数。
思路:在图中随意找一个结点进行第一次dfs,若只有一个连通分量,则找到最长子树一端的根结点,再找取这些结点中的一个进行第二次dfs,就可以找到另一端的根节点。

#include <iostream>
#include <string>
#include<algorithm>
#include<vector>
#include<utility>
#include<set>
#include<math.h>
using namespace std;
const int MAXSIZE = 10010;
const int MAX = 0x3fffffff;
int N, C, K, Q;
int visited[MAXSIZE] = { false };
vector<int> temp;
vector<vector<int> > v;
int maxheight = 0;
set<int> s;
void DFS(int vex, int height)
{
	if (height > maxheight)
	{
		temp.clear();
		temp.push_back(vex);
		maxheight = height;
	}
	else
		if (height == maxheight)
			temp.push_back(vex);
	visited[vex] = true;
	for (int i = 0; i < v[vex].size(); i++)
	{
		if (!visited[v[vex][i]])
			DFS(v[vex][i], height + 1);
	}

}

int main()
{
	int v1, v2;
	int s1,cnt=0;
	cin >> N;
	v.resize(N + 1);
	for (int i = 0; i < N - 1; i++)
	{
		cin >> v1 >> v2;
		v[v1].push_back(v2);
		v[v2].push_back(v1);
	}
	for (int i = 1; i <= N; i++)
	{
		if (!visited[i])
		{
			DFS(i, 1);
			if (i == 1)
			{
				if (!temp.empty())s1 = temp[0];
				for (int i = 0; i < temp.size(); i++)
					s.insert(temp[i]);
			}
			cnt++;
		}
	}
	if (cnt != 1)
		cout << "Error: " << cnt << " components";
	else
	{
		temp.clear();
		maxheight = 0;
		fill(visited, visited + N + 1, false);
		DFS(s1, 1);
		for (int i = 0; i < temp.size(); i++)
			s.insert(temp[i]);
		for (auto& a : s)
		{
			cout << a << endl;
		}
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值