From 2ecb2a9833e68616da7ce3625f692041038a8257 Mon Sep 17 00:00:00 2001 From: Bruno Freitas Tissei <bft15@inf.ufpr.br> Date: Tue, 13 Feb 2018 15:42:53 -0200 Subject: [PATCH] Add trees_partitions Signed-off-by: Bruno Freitas Tissei <bft15@inf.ufpr.br> --- problems/trees_partition.cpp | 79 ++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 problems/trees_partition.cpp diff --git a/problems/trees_partition.cpp b/problems/trees_partition.cpp new file mode 100644 index 0000000..fef0890 --- /dev/null +++ b/problems/trees_partition.cpp @@ -0,0 +1,79 @@ +#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; +} -- GitLab