1021 Deepest Root (25分) 注意超出内存限制和超时问题

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.

Sample Input 1:

5
1 2
1 3
1 4
2 5

Sample Output 1:

3
4
5

Sample Input 2:

5
1 3
1 4
2 5
3 4

Sample Output 2:

Error: 2 components

题目大意:

一个连通的无环图可以被看作是一棵树。树的高度取决于被选中作为根的顶点,现要求你找到可以让这棵树最高的顶点并输出。如给出的图不能构成一棵树,那么输出Error: ... components,如有多个满足条件的顶点,那么升序将它们输出。

解题思路:

最初的想法是利用邻接矩阵存储图,首先dfs判断该图是否为连通图(连通分量为1),不连通则直接Error,之后再重新从每个顶点开始进行一遍深度遍历,找到深度最大的顶点并存储下来升序输出。这样做的后果就是先出现内存超出限制(邻接矩阵导致),然后测试点3超时(N遍dfs导致)🤧

解决办法:

  1. 邻接表存储图
  2. 首先dfs计算连通分量,在该过程中利用set存储能够到达的最深的叶子结点;可以知道,如果要找到最长的一条路,必然是要到达叶子结点的,因此再从之前set存储的叶子结点中任意取出一个,再进行一次dfs遍历,将其可到达的最深的点存储在一个新的set集合中,将两个集合合并即为最深的根节点。
  3. set非常好用,可以自动排序+过滤重复的点

参考博客https://blog.csdn.net/zhang35/article/details/104198822

代码如下: 

#include<iostream>
#include<set>
#include<vector>
using namespace std; 
int n,sum = 0;
vector<int> arcs[10001];
bool visited[10001];
set<int> ans,temp;
int MAX = 0;
void dfs(int u,int length){
	visited[u] = true;
	if(length > MAX){
		ans.clear();
		ans.insert(u);
		MAX = length;
	}else if(length == MAX)
		ans.insert(u);
	for(int i = 0; i < arcs[u].size() ; i ++){
		if(!visited[arcs[u][i]])
			dfs(arcs[u][i],length+1);
	}
}
int main(){
	fill(visited,visited+10001,false);
	scanf("%d",&n);
	for(int i = 1 ; i <= n-1 ; i ++){
		int a,b;
		scanf("%d%d",&a,&b);
		arcs[a].push_back(b);
		arcs[b].push_back(a);
	}
	for(int i = 1 ; i <= n ; i ++){
		if(!visited[i]){
			dfs(i,1);
			sum ++;
		}
	}
	if(sum > 1)
		printf("Error: %d components",sum);
	else{
		fill(visited,visited+10001,false);
		temp = ans;
		ans.clear();
		dfs(*temp.begin(),1);
		for(set<int>::iterator i = temp.begin(); i != temp.end() ; ++i)
			ans.insert(*i);
		for(set<int>::iterator it = ans.begin(); it != ans.end(); ++it)
			printf("%d\n",*it);
	}
	return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值