Table of Contents

ExplanationImplementation

Hint 1

Hint 2

Explanation

We can treat each set as a graph with several connected components. For each pip_i, if apia - p_i exists, then pip_i and apia - p_i are in the same connected component inside graph AA, and similarly for BB. Each number in the connected component must belong to one set. Therefore, our condradiction comes from if there is a number xx in the component such that only axa - x exists, and another yy in the component such that only byb - y exists, or vice cersa.

We can check each component for the contradiction using DSU. The status of the whole component will be the intersection of what graph each number in the component can reside in.

Implementation

Time Complexity: O(NlogN)\mathcal{O}(N\log N)

C++

#include <bits/stdc++.h>
using namespace std;
Code Snippet: DSU (from the module) (Click to expand)
int main() {
int n, a, b;
cin >> n >> a >> b;
vector<int> p(n);
for (int i = 0; i < n; i++) { cin >> p[i]; }

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!