Explanation
Let's fix the left endpoint and compute how many right endpoints work for that . First, consider the first position such that . If this doesn't exist, let . We can't select any right endpoint , because this results in the left endpoint leader having the same breed as the cow in position . We can find this position by either binary searching the index map of or precomputation.
The right endpoint leader can be handled similarly. For all breeds in the range , we can only select the first position of that breed . Thus, the number of right endpoints that work for this are the number of distinct elements in . This can be found using a data structure like a BIT (Binary Indexed Tree).
We sweep from left to right, and maintain the BIT accordingly by inserting breeds as we go. This ensures we don't overcount delegations, and allows us to efficiently query the number of valid right endpoints for each fixed .
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;Code Snippet: BIT (Click to expand)int main() {int n;cin >> n;vector<int> breed(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!