1021

本文深入探讨了图遍历算法及其在解决特定问题中的应用,特别是在使用深度优先搜索(DFS)进行最远节点查找的过程中。此外,文章详细讲解了并查集数据结构的实现与优化,包括路径压缩技巧,以及如何利用并查集处理连通性问题,确保图中所有节点属于同一连通分量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn = 10010;
vector <int> G[maxn];
int father[maxn];
vector<int> temp,root;
int n;
int maxh = -1;
int findfather(int n)
{
	int x = n;
	while(x != father[x])
	{
		x = father[x];
	}
	int a = n;
	while(father[a] != a)
	{
		int z = a;
		a = father[a];
		father[z] = x;
	}
	return x;
}
void Union(int a,int b)
{
	int faa = findfather(a),fbb = findfather(b);
	if(faa != fbb) father[faa] = fbb;
}
void dfs(int u,int h,int pre)
{
	if(h > maxh)
	{
		temp.clear();
		maxh = h;
		temp.push_back(u);
	}
	else if(h == maxh)
	{
		temp.push_back(u);
	}
	for(int i = 0; i < G[u].size(); i++)
	{
		 if(G[u][i] != pre)
		 {
	//	 	printf("%d",G[u][i]);
		 	dfs(G[u][i],h+1,u);
		 	
		 }
		    
	}
}
int main()
{
	scanf("%d",&n);
	for(int i = 1; i <= n; i++)
	{
		father[i] = i;
	}
	int u,v;
	for(int i = 1; i < n; i++)
	{
		scanf("%d %d",&u,&v);
        G[u].push_back(v);	
     	G[v].push_back(u);
     	
    	Union(u,v);
	}
	int sum = 0;
	for(int i = 1; i <= n; i++)
	{
		if(findfather(i) == i)
		{
			sum++;
		}
	}
	if(sum > 1)
	{
		printf("Error: %d components\n",sum);
		return 0;
	}
	dfs(1,1,-1);
	root = temp;	
	dfs(root[0],1,-1);
	for(int i = 0; i < temp.size(); i++)
	{
		root.push_back(temp[i]);
	}
	int len = root.size();
	sort(root.begin(),root.end());
	for(int i = 0; i < len; i++)
	{
		if(i >= 1 && root[i] == root[i-1]) continue;
		printf("%d\n",root[i]);
	}
	   
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值