Official Analysis

Implementation

Time complexity: O(NlogN+QlogN)\mathcal{O}(N \log N + Q \log N). O(NlogN)\mathcal{O}(N \log N) from generating the sparse tables, and O(QlogN)\mathcal{O}(Q \log N) from processing the LCA.

C++

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int MOD = 1e9 + 7;
Code Snippet: ModInt (Click to expand)
// equivalent to dividing by 1000000

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!