Official Analysis

Implementation

As explained in the official analysis, when we use small to large merging on data structures such as sets and maps, we optimize the amount of operations from O(N2logN)\mathcal{O}(N^2 \log N) to O(Nlog2N)\mathcal{O}(N \log^2 N). We can take advantage of this to store all kinds of information related to colors, their sum, and their occurrences.

Time Complexity: O(Nlog2N)\mathcal{O}(N \log^2 N)

C++

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int MAX_N = 1e5;
array<ll, MAX_N> color;
array<ll, MAX_N> ans;
vector<int> g[MAX_N];

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!