diff --git a/problems/trees_partition.cpp b/problems/trees_partition.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..fef08902ded6c5eaf4bc3257e625feb59d53256e
--- /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;
+}