Explanation
There are two parts in solving this problem. First, we need to efficiently determine whether a given value of is valid. Second, we need to efficiently find the smallest such which is valid.
We start by determining if a given is valid. We can simulate the cows dancing on stage and then leaving, and whenever cows are on stage, we want to find the earliest time a cow leaves the stage (when the next cow can join). This motivates using a priority queue, which supports efficient insertion and removal of its minimum element. Therefore, checking whether is valid takes time.
Now, we wish to determine the minimum value of which is valid. Remember that is guaranteed to be a valid value.
Observe that if is valid, then so is , since having an extra spot cannot make the cows dance later than they originally would. Therefore, we can binary search for the smallest such , which is fast enough to solve the problem.
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;int main() {freopen("cowdance.in", "r", stdin);freopen("cowdance.out", "w", stdout);int n, t;cin >> n >> t;int ar[n];
Python
import heapqwith open("cowdance.in") as r:n, maximum = map(int, r.readline().split())dance = [int(r.readline()) for _ in range(n)]left = 1right = n + 1while left < right:mid = (left + right) // 2
Java
import java.io.*;import java.util.*;public class CowDanceShow {static int[] danceTimes;static int n;static int maxTime;static boolean isOk(int stageSize) {PriorityQueue<Integer> currentDancing = new PriorityQueue<>();
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!