P2678: Jumping Stones — Solution & the Principle of Binary Search on the Answer
This problem was handed out when I was training with the godlike elementary schoolers over the summer, and I never knew how to solve it. A month ago the big shot crazydave gave me a quick rundown of how binary search on the answer works, and I, a weakling, only got it all sorted out today.
Let’s look at the example problem first: Luogu P2678
This is an easy problem from the NOIP Senior Division (I’m way too weak). The main idea is to enumerate the answer and, at each step of the enumeration, just check whether it meets the requirements. Code first:
// P2678.cpp
#include <iostream>
using namespace std;
const int maxn = 500020;
int L, N, M;
int D[maxn];
bool check(int num)
{
int last = 0;
int cnt = 0;
for (int i = 0; i <= N; i++)
if (D[i] - last < num)
cnt++;
else
last = D[i];
if (cnt > M)
return false;
return true;
}
void solve()
{
int left = 0;
int right = L;
int ans = 0;
while (left <= right)
{
int mid = (left + right) / 2;
if (check(mid))
left = mid + 1, ans = mid;
else
right = mid - 1;
}
cout << ans;
}
int main()
{
cin >> L >> N >> M;
for (int i = 0; i < N; i++)
cin >> D[i];
D[N] = L;
solve();
return 0;
}
The check function verifies whether the answer num (that is, the answer we enumerated) meets the requirements; here, that means checking whether, when the minimum distance is num, the stones removed exceed the limit. If they do, it returns false, and the binary search adjusts the interval to [left,mid-1], lowering the maximum to probe the limit; if they don’t, it returns true, and the binary search adjusts the interval to [mid+1,right], in pursuit of a larger maximum.
Abstracted Analysis Results
Before you set out to enumerate the answer to a problem, consider binary search on the answer. If binary search on the answer works, the time complexity drops drastically, from O(n^2) to O(n log n). The structure of binary search on the answer is just the binary search code plus the code that checks whether an answer is correct. If an answer passes the correctness check, go for a larger (smaller) answer and enumerate again; if it fails, adjust the interval and go for a larger (smaller) answer within the smaller (larger) interval. And so on, over and over.