Table of Contents

ExplanationImplementation

Official Analysis (C++, Java)

Explanation

Let's fix the left endpoint ll and compute how many right endpoints rr work for that ll. First, consider the first position x>lx>l such that bx=blb_x=b_l. If this doesn't exist, let x=N+1x = N + 1. We can't select any right endpoint rxr \ge x, because this results in the left endpoint leader having the same breed as the cow in position xx. We can find this position xx by either binary searching the index map of bb or precomputation.

The right endpoint leader can be handled similarly. For all breeds in the range (l,x)(l, x), we can only select the first position of that breed >l>l. Thus, the number of right endpoints that work for this ll are the number of distinct elements in (l,x)(l, x). 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 ll.

Implementation

Time Complexity: O(NlogN)\mathcal{O}(N\log N)

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!