Explanation
We can subtract from each query, sort the cities by occurrences and the queries by year, and then answer the queries offline.
Let city denote the 'th smallest city sorted by occurrences, and represent the number of occurrences. We can loop through each and track the years that have passed.
Assume cities already have occurrences. For them to all end up with occurrences, we need more years, meaning that for the next years, cities will be selected one after another.
To answer individual years, we can use a BST to track the initial indices of each city . Note that initial indices, not the sorted ones, break the tie for occurrences.
Let the current year be . At each iteration, we can answer every query in the range of and use binary search to obtain the indices of these queries. Since these cities are selected one after another, the answer to query is just the '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 is just .
Implementation
Time Complexity:
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!