『缩点·树的直径』CF734E Anton and Tree

P r o b l e m \mathrm{Problem} Problem

给一棵 n ( n ≤ 200000 ) n(n\le 200000) n(n200000)个节点的树,每个点为黑色或白色。

一次操作可以使一个相同颜色的连通块变成另一种颜色。

求使整棵树变成一种颜色的最少操作数。


S o l u t i o n \mathrm{Solution} Solution

使用并查集缩点,使得任意相邻的两点颜色都不一样。

可以证明,从树的直径的终点开始染色一定是最优的。
在这里插入图片描述
其中 L 3 L_3 L3 是直径上的最后一段,显然有 L 1 , 2 ≤ L 3 L_{1,2}\le L_3 L1,2L3

且分叉出去的节点颜色是相同的,那么这意味着在完成 L 3 L_3 L3染色之前, L 1 / L 2 L_1/L_2 L1/L2的染色一定会被染色完成。

观察规律,我们发现答案一定是: ⌊ ( m a x l e n + 1 ) / 2 ⌋ \lfloor (\mathrm{maxlen+1})/2 \rfloor (maxlen+1)/2


C o d e \mathrm{Code} Code

#include <bits/stdc++.h>

using namespace std;
const int N = 5e5;

int n, res;
int f[N], fa[N], x[N], y[N], col[N];
vector < int > a[N];

long long read(void)
{
	int s = 0, w = 0; char c = getchar();
	while (c < '0' || c > '9') w |= c == '-', c = getchar();
	while (c >= '0' && c <= '9') s = s*10+c-48, c = getchar();
	return w ? -s : s;
}

void Dfs(int x, int fa)
{
	f[x] = 0;
	for (int i=0;i<a[x].size();++i)
	{
		int y = a[x][i];
		if (y == fa) continue;
		Dfs(y, x);
		res = max(res, f[x] + f[y] + 1);
		f[x] = max(f[x], f[y] + 1);
	}
	return;
}

int get(int x) {
	if (fa[x] == x) return x;
	return fa[x] = get(fa[x]);
}
 
int main(void)
{
	n = read();
	for (int i=1;i<=n;++i) {
		col[i] = read();
		fa[i] = i;
	}
	for (int i=1;i<n;++i) {
		x[i] = read(), y[i] = read();
		if (col[x[i]] == col[y[i]]) fa[get(x[i])] = get(y[i]); 
	} 
	for (int i=1;i<n;++i) 
	{
		x[i] = get(x[i]);
		y[i] = get(y[i]);
		if (x[i] == y[i]) continue;
		a[x[i]].push_back(y[i]);
		a[y[i]].push_back(x[i]);
	}
	Dfs(get(1), 0);
	cout << (res + 1 >> 1);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值