1021 Deepest Root (25 分)DFS+邻接矩阵

18 篇文章 0 订阅
7 篇文章 0 订阅

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
#include <iostream>
#include <bits/stdc++.h>

using namespace std;
const int maxn = 1e4+10;
std::vector<std::vector<int> > vec(maxn);
bool vis[maxn];
int height[maxn];
int num = 0;
int N;
void dfs(int pos){
	vis[pos] = true;
	for(auto it = vec[pos].begin();it!=vec[pos].end();it++)
		if(vis[*it] == false)
			dfs(*it);
}
int calc(int pos,int num){
	int max_val = num;
	vis[pos] = true;
	for(auto it = vec[pos].begin();it!=vec[pos].end();it++)
		if(vis[*it]==false)
			max_val = max(max_val,calc(*it,num+1));
	return max_val;
}
int main(int argc, char const *argv[])
{
	

	cin>>N;
	for (int i = 0; i < N-1; ++i)
	{
		int u,v;
		cin>>u>>v;
		vec[u].push_back(v);
		vec[v].push_back(u);
	}
	for(int i = 1;i<=N;i++)
		if(vis[i] == false){
			dfs(i);
			num++;
		}
	if(num >1){
		cout<<"Error: "<<num<<" components"<<endl;
		return 0;
	}
	int max_val = 0;
	for(int i = 1;i<=N;i++)
	{
		memset(vis,0,sizeof(vis));
		height[i] = calc(i,0);
		max_val = max(max_val,height[i]);
	}
	for (int i = 1; i <=N; ++i)
	{
		if(height[i] == max_val)
			cout<<i<<endl;
	}
	return 0;
}

解题思路

先对每个顶点都进行DFS遍历计算联通数量,大于1直接就不用搜了。然后对每个节点进行其最大深度的计算,本代码中用了分治的思想, max_val = max(max_val,calc(j,num+1)),递归第i个节点的邻接节点j 计算这个节点往下搜索的深度最大值,然后保存下来并进行比较,题目返回最大深度。

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值