[Codeforces Round #395 (Div. 1)] - D Timofey and a flat tree

本文分享了一种解决树哈希问题的创新方法,通过为不同大小的树分配随机值并进行加减运算,简化了处理子树问题的过程。利用unordered_map进行高效查找,展示了完整的代码实现。

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

洛谷传送门
Codeforces传送门

题目大意

给你一棵 n n n个节点的无根树, 现在要你定一个根节点, 满足其不同构的子树的数量最大。

输入输出格式

输入格式

第一行一个正整数 n n n
以下 n − 1 n-1 n1行, 每行两个正整数 a i , b i a_i,b_i ai,bi, 描述一组树上的边。

输出格式

一行一个正整数, 表示选定的根节点。 如果有多解输出一个即可。

输入输出样例

输入样例#1:
3
1 2
2 3
输出样例#1:
1
输入样例#2:
7
1 2
4 2
2 3
5 6
6 7
3 7
输出样例#2:
1
输入样例#3:
10
1 7
1 8
9 4
5 1
9 2
3 5
10 6
10 9
5 10
输出样例#3:
2

解题分析

树哈希模板题, 学到了一种骚操作。

直接每个大小的树给一个随机值, 然后加起来…这样就很好处理加减子树的问题。

然后开个 m a p map map随便搞搞就好了。

代码如下:

#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <vector>
#include <ctime>
#include <unordered_map>
#include <algorithm>
#define R register
#define IN inline
#define W while
#define MX 100500
#define gc getchar()
#define rd rand
#define ll long long
template <class T>
IN void in(T &x)
{
	x = 0; R char c = gc;
	for (; !isdigit(c); c = gc);
	for (;  isdigit(c); c = gc)
	x = (x << 1) + (x << 3) + c - 48;
}
int n, dif, ans, mx = -1, cnt;
std::unordered_map <ll, int> mp;
std::vector <int> nex[MX];
ll base[MX << 1], hs[MX];
int ct[MX << 1];
IN void add(R int from, R int to) {nex[from].emplace_back(to);}
IN int Get(R ll val) {if (!mp.count(val)) mp[val] = ++cnt; return mp[val];}
IN void insert(R int v) {if (!ct[v]) ++dif; ct[v]++;}
IN void erase(R int v) {--ct[v]; if (!ct[v]) --dif;}
void DFS(R int now, R int fa)
{
	ll sum = 0;
	for (auto i : nex[now])
	{
		if (i == fa) continue;
		DFS(i, now);
		sum += base[hs[i]];
	}
	insert(hs[now] = Get(sum));
}
void calc(R int now, R int fa, R int up)
{
	erase(hs[now]);
	if (dif > mx) mx = dif, ans = now;
	ll sum = 0, tar;
	for (auto i : nex[now])
	{
		if (i == fa) continue;
		sum += base[hs[i]];
	}
	sum += base[up];
	for (auto i : nex[now])
	{
		if (i == fa) continue;
		tar = sum - base[hs[i]];
		insert(Get(tar));
		calc(i, now, Get(tar));
		erase(Get(tar));
	}
	insert(hs[now]);
}
int main(void)
{
	in(n); int foo, bar;
	srand(time(NULL));
	for (R int i = 1; i <= (n << 1); ++i)
	base[i] = ((1ull * (rd() * rd() + rd()) * rd()) + rd() * rd()) % LONG_LONG_MAX;
	for (R int i = 1; i < n; ++i)
	{
		in(foo), in(bar);
		add(foo, bar), add(bar, foo);
	}
	DFS(1, 0);
	calc(1, 0, 0);
	printf("%d", ans);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值