CF - Duff in the Army

Author: Chongtian Ma

Table of Contents

ExplanationImplementation

Official Analysis

Explanation

Note that for each two nodes uu and vv, the path between them is just uu to lca(u,v)lca(u,v) and vv to lca(u,v)lca(u,v). Also note the constraint of a10a \leq 10 for each query. To answer each query, we only need to store the 1010 people with the smallest ids for the path from uu to lca(u,v)lca(u,v) and vv to lca(u,v)lca(u,v), and combine them. This can be done with binary lifting, which will store the 1010 smallest ids for each vertex to their 2k2^k'th ancestor.

Implementation

We can answer each query in O(alogn)\mathcal{O}(a \log n). Even though the constant factor is pretty bad, the problem limits give room for it. Note that if you do store more than 1010 smallest ids the problem will yield a MLE!

Time Complexity: O(alogn)\mathcal{O}(a \log n) for each query.

C++

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 1;
const int MAXL = 20; // approximately maximum log
// for euler-tour
array<int, MAXN> enter_time, exit_time, depth;
int timer = 1;
// for binary lifting

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!