学习笔记:树的重心

给定一颗树,树中包含n个结点(编号1~n)和n-1条无向边。
请你找到树的重心,并输出将重心删除后,剩余各个连通块中点数的最大值。

重心定义:重心是指树中的一个结点,如果将这个点删除后,剩余各个连通块中点数的最大值最小,那么这个节点被称为树的重心。

输入格式
第一行包含整数n,表示树的结点数。
接下来n-1行,每行包含两个整数a和b,表示点a和点b之间存在一条边。

输出格式
输出一个整数m,表示将重心删除后,剩余各个连通块中点数的最大值。

思路:枚举每一个点被删除后的情况,计算联通块中的点数,在树中删除一个点后,联通块的情况:点u的每一个子树是一个联通块,同时除了剩余的除了点u及其子树外是另一个联通块

#include<cstdio>
#include<cmath>
#include<ctime>
#include<cstring>
#include<iostream>
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<string>
#include<vector>
#define ll long long
#define ull unsigned long long
#define up_b upper_bound
#define low_b lower_bound
#define m_p make_pair
#define mem(a) memset(a,0,sizeof(a))
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define inf 0x3f3f3f3f
#define endl "\n"
#include<algorithm>
using namespace std;

inline ll read()
{
	ll x=0,f=1; char ch=getchar();
	while(ch<'0'||ch>'9')	{ if(ch=='-') f=-1; ch=getchar(); }
	while('0'<=ch&&ch<='9')	x=x*10+ch-'0', ch=getchar();
	return f*x;
}

const int N = 1e5+5;

int n;
bool vis[N];
struct node{int v,next;}edge[2*N];
int head[N],idx;

void add(int u,int v)
{
	edge[idx]=(node){v,head[u]};
	head[u]=idx++;
}

int ans=inf;

int dfs(int u) //dfs的返回值是以点u为为根节点的子树的大小
{
	vis[u]=true; //标记该点被访问
	
	int sum=1,res=0;
	//sum存以点u为为根节点的子树的大小,首先将自己算上,sum=1
	//res存删除点u后,所以联通块中的最大值
	
	for(int i=head[u];~i;i=edge[i].next)
	{
		int v=edge[i].v;
		if(vis[v])	continue;
		int t=dfs(v);
		res=max(res,t); //在其子树形成的联通块中取一个最大值
		sum+=t;
	}
	res=max(res,n-sum); //除了点u及其子树外的另一个联通块
	ans=min(res,ans); //最终答案在所有res中取一个最小值
	return sum;
}

int main()
{
	memset(head,-1,sizeof(head));
	
	cin>>n;
	for(int i=1;i<n;i++)
	{
		int u=read(),v=read();
		add(u,v); add(v,u); //树是无向图,建立双向边
	}
	dfs(1); //遍历整个树,从那个点开始都可以
	cout<<ans<<endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值