BRKFLP - Editorial

PROBLEM LINK:

Practice
Contest: Division 1
Contest: Division 2
Contest: Division 3
Contest: Division 4

Author: hyder1102
Tester: raysh07
Editorialist: iceknight1093

DIFFICULTY:

TBD

PREREQUISITES:

DSU, trees

PROBLEM:

You’re given a tree.
Each vertex is either black or white initially.

Process Q updates/queries.

  1. Given u and v, remove the edge between u and v.
  2. Flip the color of every vertex that has been touched by a type 1 operation.
  3. Report the number of good vertices.
    A vertex is good iff it can reach an odd number of black vertices.

EXPLANATION:

At any point of time, we’ll have a forest.
For a vertex to be good, there must hence be an odd number of black vertices in its component; and if this is the case, every vertex in this component will be good.
Thus, either everything in a component is good, or nothing is good.

Also, it’s generally harder to deal with edge removals as compared to edge insertions (for which DSU is a powerful tool.)
Luckily, this problem doesn’t force us to answer queries online, so we can instead work in reverse.

Working in reverse, we start out with N singletons, and then need to process updates: merging two components together, and flipping the colors of some vertices.
While doing this we also need to maintain some information about each component, to know whether it is good or not.


First, let’s compute for each vertex the first time it is affected by a type 1 operation (its “activation time”), as well as its final color (which depends on the number of type 2 operations after its activation time.)
This gives us the initial state for the reverse-processing.

We now need to process component merges and color flips of activated vertices; as well as being able to deactivate vertices when needed.

Since the color of each vertex at any point of time depends only on the parity of the number of operations done after it, and we’re working with suffixes, we only need to care about the parity of operations so far.

So, for each component, we’ll store values corresponding to two separate states: one for an even parity of flips, and one for an odd parity.
If we’re able to do this, then the type 2 update becomes trivial - we can just flip the parity and nothing else needs to be done (since answers are stored for both parities already), so it’s actually constant time.
Similarly, type 3 queries are trivial, since we have the answers already and just need to output them.

That leaves merges (and deactivations) for us to handle.
This is not too hard.
In particular, you will find that it’s enough to store, for each component, the following information:

  • The (parity of the) count of black vertices in it.
  • The (parity of the) count of activated vertices in it.
  • Its contribution, either 0 or its size.
    • This contribution needs to be stored for both parities of flip operations.

Merging two components is then quite easy, the details are left as an exercise to the reader.

The complexity of this is whatever is the complexity of the DSU you use.

TIME COMPLEXITY:

\mathcal{O}((N+Q)\alpha(N)) per testcase.

CODE:

Tester's code (C++)
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define INF (int)1e18

mt19937_64 RNG(chrono::steady_clock::now().time_since_epoch().count());

void Solve() 
{
    int n, q; cin >> n >> q;
    string s; cin >> s;
    s = "0" + s;
    
    vector <int> deg(n + 1);
    for (int i = 1; i < n; i++){
        int u, v; cin >> u >> v;
        deg[u]++;
        deg[v]++;
    }
    
    vector <array<int, 3>> vec(q);
    vector <int> ps(q);
    vector <int> ff(n + 1, -1);
    for (int i = 0; i < q; i++){
        int t; cin >> t;
        int x, y;
        if (t == 1){
            cin >> x >> y;
            if (ff[x] == -1) ff[x] = i;
            if (ff[y] == -1) ff[y] = i;
        }
        ps[i] = (t == 2);
        if (i > 0) ps[i] += ps[i - 1];
        vec[i] = {t, x, y};
    }
    
    for (int i = 1; i <= n; i++){
        int changes = ps[q - 1] - ps[ff[i]];
        if (changes % 2 == 1){
            s[i] ^= 'B' ^ 'W';
        }
    }
    
    reverse(vec.begin(), vec.end());
    vector <int> lst;
    
    // in each component, maintain parity of blacks, and number of vertices with deg > 0, size of component and last type-2 update 
    int curr = 0;
    vector <int> ans(2, 0);
    vector <int> root(n + 1);
    for (int i = 1; i <= n; i++) root[i] = i;
    
    struct info{
        int last;
        int black, flip, sz;
    };
    
    vector <info> ds(n + 1);
    
    auto refresh = [&](info a){
        info c = a;
        if ((curr - a.last) % 2 == 1 && a.flip % 2 == 1){
            c.black ^= 1;
        }
        return c;
    };
    
    auto add = [&](info a, int v){
        if (a.last % 2 == 0){
            ans[0] += v * (a.black % 2 == 1) * a.sz;
            ans[1] += v * ((a.black ^ a.flip) % 2 == 1) * a.sz;
        } else {
            ans[1] += v * (a.black % 2 == 1) * a.sz;
            ans[0] += v * ((a.black ^ a.flip) % 2 == 1) * a.sz;
        }
    };
    
    auto merge = [&](info a, info b, int modify){
        info c;
        add(a, -1);
        add(b, -1);
        a = refresh(a);
        b = refresh(b);
        c.black = a.black ^ b.black;
        c.flip = a.flip ^ b.flip;
        c.flip ^= modify;
        c.sz = a.sz + b.sz;
        c.last = curr;
        add(c, 1);
        return c;
    };
    
    auto find = [&](auto self, int x){
        if (root[x] == x) return x;
        return root[x] = self(self, root[x]);
    };  
    
    for (int i = 1; i <= n; i++){
        ds[i].last = 0;
        ds[i].black = (s[i] == 'B');
        ds[i].flip = 1;
        ds[i].sz = 1;
        add(ds[i], +1);
    }
    
    for (auto [t, x, y] : vec){
        if (t == 1){
            deg[x]--;
            deg[y]--;
            int modify = (deg[x] == 0) ^ (deg[y] == 0);
            x = find(find, x);
            y = find(find, y);
            
            ds[x] = merge(ds[x], ds[y], modify);
            root[y] = x;
        } else if (t == 2){
            curr += 1;
        } else {
            lst.push_back(ans[curr % 2]);
        }
    }
    
    reverse(lst.begin(), lst.end());
    for (auto x : lst) cout << x << "\n";
}

int32_t main() 
{
    auto begin = std::chrono::high_resolution_clock::now();
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int t = 1;
    // freopen("in",  "r", stdin);
    // freopen("out", "w", stdout);
    
    cin >> t;
    for(int i = 1; i <= t; i++) 
    {
       // cout << "Case #" << i << ": \n";
        Solve();
    }
    auto end = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);
    cerr << "Time measured: " << elapsed.count() * 1e-9 << " seconds.\n"; 
    return 0;
}