Skip to content
Snippets Groups Projects
Commit 2ecb2a98 authored by Bruno Freitas Tissei's avatar Bruno Freitas Tissei
Browse files

Add trees_partitions

parent c2250cd9
No related branches found
No related tags found
No related merge requests found
#include <bits/stdc++.h>
#define MAX 301010
using namespace std;
#define fi first
#define se second
#define mp make_pair
#define pb push_back
typedef unsigned long long ll;
typedef pair<ll,ll> ii;
vector<int> t1[MAX], t2[MAX];
ll hsh[MAX];
unordered_map<ll, int> M;
ll ans = 0, tot = 0;
ll dfs(int x, int par) {
ll down = hsh[x];
for (auto i : t1[x]) {
if (i != par) {
ll bel = dfs(i, x);
down ^= bel;
M[bel] = 1;
}
}
return down;
}
ll solve(int x, int par) {
ll down = hsh[x];
for (auto i : t2[x]) {
if (i != par) {
ll bel = solve(i, x);
down ^= bel;
if (M[bel] || M[bel ^ tot]) {
ans++;
M[bel] = M[bel ^ tot] = 0;
}
}
}
return down;
}
int main() {
int n, x;
scanf("%d", &n);
mt19937_64 mt(time(NULL));
for (int i = 0; i < n - 1; ++i) {
scanf("%d", &x);
t1[i+1].pb(x-1);
t1[x-1].pb(i+1);
}
for (int i = 0; i < n - 1; ++i) {
scanf("%d", &x);
t2[i+1].pb(x-1);
t2[x-1].pb(i+1);
}
for (int i = 0; i < n; ++i) {
hsh[i] = mt();
tot ^= hsh[i];
}
dfs(0, -1);
solve(0, -1);
printf("%lld\n", ans);
return 0;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment