1709E - XOR Tree - CodeForces Solution


bitmasks data structures dfs and similar dsu greedy trees *2400

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
#include <bits/extc++.h>

using namespace std;
using namespace __gnu_pbds;

// template <typename T>
// using ordered_multiset = tree<T, null_type, less_equal<T>,
// 			      rb_tree_tag, tree_order_statistics_node_update>;

using ll = long long;

using pii = pair<int, int>;
#define mp make_pair
#define xx first
#define yy second

#define pb emplace_back
#define sz(x) int(x.size())

const int INF = 0x3f3f3f3f;
const int N = 2e5 + 5;

set<ll> dp[N];
vector<int> graph[N];
ll a[N], b[N];

void dfs(int u, int par, int &ret) {
  b[u] = (par == -1) ? b[par] : (b[par] ^ a[u]);
  dp[u].insert(b[u]);

  bool change = false;

  for (int v : graph[u]) {
    if (v == par) continue;
    dfs(v, u, ret);

    if (sz(dp[u]) < sz(dp[v]))
      swap(dp[u], dp[v]);
    
    for (int x : dp[v])
      if (dp[u].count(x ^ a[u]))
	change = true;

    for (int x : dp[v])
      dp[u].insert(x);
  }
 
  if (change) {
    ++ret;
    dp[u].clear();
  }
}

void solve() {
  int n;
  cin >> n;

  for (int i = 0; i < n; ++i)
    cin >> a[i];
  
  for (int i = 0; i < n - 1; ++i) {
    int u, v;
    cin >> u >> v;
    --u, --v;
    graph[u].pb(v);
    graph[v].pb(u);
  }

  int ret = 0;
  dfs(0, -1, ret);
  cout << ret << '\n';
}

int main() {
  cin.tie(0)->sync_with_stdio(0);
  solve();
}


Comments

Submit
0 Comments
More Questions

1452A - Robot Program
344A - Magnets
96A - Football
702B - Powers of Two
1036A - Function Height
443A - Anton and Letters
1478B - Nezzar and Lucky Number
228A - Is your horseshoe on the other hoof
122A - Lucky Division
1611C - Polycarp Recovers the Permutation
432A - Choosing Teams
758A - Holiday Of Equality
1650C - Weight of the System of Nested Segments
1097A - Gennady and a Card Game
248A - Cupboards
1641A - Great Sequence
1537A - Arithmetic Array
1370A - Maximum GCD
149A - Business trip
34A - Reconnaissance 2
59A - Word
462B - Appleman and Card Game
1560C - Infinity Table
1605C - Dominant Character
1399A - Remove Smallest
208A - Dubstep
1581A - CQXYM Count Permutations
337A - Puzzles
495A - Digital Counter
796A - Buying A House