Table of Contents

ExplanationImplementation

Official Analysis

Explanation

We can subtract nn from each query, sort the cities by occurrences and the queries by year, and then answer the queries offline.

Let city ii denote the ii'th smallest city sorted by occurrences, and occiocc_i represent the number of occurrences. We can loop through each ii and track the years that have passed.

Assume cities 1,2,i1, 2, \dots i already have occiocc_i occurrences. For them to all end up with occi+1occ_{i+1} occurrences, we need i(occi+1occi)i \cdot (occ_{i+1} - occ_i) more years, meaning that for the next i(occi+1occi)i \cdot (occ_{i+1} - occ_i) years, cities 1,2,i1, 2, \dots i will be selected one after another.

To answer individual years, we can use a BST to track the initial indices of each city 1,2,3i1, 2, 3 \dots i. Note that initial indices, not the sorted ones, break the tie for occurrences.

Let the current year be yy. At each iteration, we can answer every query qq in the range of yq<y+i(occi+1occi)y \leq q < y + i \cdot (occ_{i+1} - occ_i) and use binary search to obtain the indices of these queries. Since these cities are selected one after another, the answer to query qq is just the (qy)%i(q - y) \% i'th city sorted by initial indices.

At this point, we know every city has the max occurrence, so the answer to remaining queries that ask for years after the final yy is just (qy)%m(q - y) \% m.

Implementation

Time Complexity: O(mlogqlogm)\mathcal{O}(m \log q \log m)

C++

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/detail/standard_policies.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
using ll = long long;
#define all(x) x.begin(), x.end()

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!