Official

E - 2xN Grid Editorial by en_translator


For a run-length compression \(\widetilde{A}=(x _ i,l _ i) _ {1\leq i\leq n}\) of \(A=(a _ 1,\ldots,a _ l)\), let \(I _ A=(I _ {A,i}) _ {0\leq i\leq n}=\left(\displaystyle\sum _ {1\leq j\leq i}l _ j\right) _ {0\leq i\leq n}\). Then, for \(j=1,2,\ldots,n\), the value \(a _ i\) for all \(i\) such that \(I _ {A,j-1}\lt i\leq I _ {A,j}\) are equal.

For \(R _ 1\) and \(R _ 2\) that represents the sequence in the first and second row, let \(I=(I _ 0,\ldots,I _ {N _ 1+N _ 2+1})\) be a sorted sequence obtained by merging \(I _ {R _ 1},I _ {R _ 2}\). Then, for \(j=1,2,\ldots N _ 1+N _ 2+1\), the pair of values \((R _ {1,i},R _ {2,i})\) for all \(i\) such that \(I _ {j-1}\lt i\leq I _ j\) are all equal.

Therefore, this problem has been solved by, for each \(I _ j\), adding \(I _ j-I _ {j-1}\) to the answer if \(R _ {1,I _ j}=R _ {2,I _ j}\).

The time complexity is \(O(N _ 1+N _ 2)\).

The following is a sample code. The implementation uses the fact that, for non-negative integers \(i\) and \(j\), we always have \(i=j\iff i\operatorname{xor}j=0\).

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    using namespace std;

    unsigned long L;
    unsigned N, M;
    cin >> L >> N >> M;

    vector<pair<unsigned long, unsigned>> A(N), B(M);
    for (auto&&[l, v] : A)
        cin >> v >> l;
    for (auto&&[l, v] : B)
        cin >> v >> l;
    A.emplace(begin(A));
    B.emplace(begin(B));

    for (unsigned i{}; i < N; ++i) {
        A[i + 1].first += A[i].first;
        A[i].second ^= A[i + 1].second;
    }
    for (unsigned i{}; i < M; ++i) {
        B[i + 1].first += B[i].first;
        B[i].second ^= B[i + 1].second;
    }

    vector<pair<unsigned long, unsigned>> C(N + M + 2);
    merge(begin(A), end(A), begin(B), end(B), begin(C));

    for (unsigned i{}; i < N + M + 1; ++i) {
        C[i].first = C[i + 1].first - C[i].first;
        C[i + 1].second ^= C[i].second;
    }
    C.pop_back();

    unsigned long ans{};
    for (const auto&[l, c] : C)
        if (c == 0)
            ans += l;

    cout << ans << endl;

    return 0;
}

posted:
last update: