Fork me on GitHub

Codeforces763D

Codeforces763D题解

题意:

  • 给定一棵树,询问以哪个点为根时其不同构子树数量最多。

题解:

  • $n$个点的树,$n-1$条边,所以子树共有$2(n-1)$种。
  • 然后先维护出以$1$为根的各子树哈希值。
  • 然后在跑一遍$dfs$算出每个点的答案就可以啦。

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <bits/stdc++.h>
#define gc getchar()
#define ll unsigned long long
#define N 200009
using namespace std;
int n,num[N],diff,first[N],number,Max,Ans,cnt,f[N];
ll val[N];
map<ll,int> mp;
struct edge
{
int to,next;
void add(int x,int y)
{
to=y,next=first[x],first[x]=number;
}
}e[N<<1];
int read()
{
int x=1;
char ch;
while (ch=gc,ch<'0'||ch>'9') if (ch=='-') x=-1;
int s=ch-'0';
while (ch=gc,ch>='0'&&ch<='9') s=s*10+ch-'0';
return s*x;
}
void add(int x)
{
if (!(num[x]++)) diff++;
}
void del(int x)
{
if (!(--num[x])) diff--;
}
int get(int x)
{
return mp.count(x)?mp[x]:mp[x]=++cnt;
}
void dfs(int x,int fa)
{
ll sum=0;
for (int i=first[x];i;i=e[i].next)
if (e[i].to!=fa) dfs(e[i].to,x),sum+=val[f[e[i].to]];
f[x]=get(sum);
add(f[x]);
}
void get_Ans(int x,int fa,int out)
{
del(f[x]);
if (diff+1>Max) Max=diff+1,Ans=x;
ll sum=0;
for (int i=first[x];i;i=e[i].next)
if (e[i].to!=fa) sum+=val[f[e[i].to]];
sum+=val[out];
for (int i=first[x];i;i=e[i].next)
if (e[i].to!=fa)
{
ll sum_now=sum-val[f[e[i].to]];
add(get(sum_now));
get_Ans(e[i].to,x,get(sum_now));
del(get(sum_now));
}
add(f[x]);
}
int main()
{
n=read();
for (int i=1;i<=2*n;i++) val[i]=(1+rand())*23333LL+(rand()*7ll+129873123LL)+((rand()+1243)<<30);
for (int i=1;i<n;i++)
{
int x=read(),y=read();
e[++number].add(x,y);
e[++number].add(y,x);
}
dfs(1,0);
get_Ans(1,0,0);
printf("%d\n",Ans);
return 0;
}
-------------本文结束感谢您的阅读-------------

本文标题:Codeforces763D

文章作者:wzf2000

发布时间:2017年12月26日 - 12:12

最后更新:2017年12月26日 - 12:12

原始链接:https://wzf2000.github.io/2017/12/26/Codeforces763D/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。