APIO 2015 - Palembang Bridges
Author: Andi Qu
Time Complexity:
Since people only cross bridges when their two buildings are on opposite sides of the river, assume without loss of generality that all the people must cross a bridge.
If the bridge is at position , then the total cost would be . Clearly, this value is minimized when is the median of all and .
We can find the median simply by sorting all the numbers in the input.
Since each person crosses exactly one bridge, which one would person choose? The answer is that they'd choose the bridge that is closest to .
This means that if we sort the people by , then we can split them into a prefix where people choose bridge 1 and a suffix where people choose bridge 2. Notice how we can use our solution for to compute the answer for each bridge.
Now we can simply try out all the places to split the people into prefix and suffix. To maintain a sliding median, we can use two std::priority_queue
s. (For more details, see CSES Sliding Median)
1#include <bits/stdc++.h>2#define FOR(i, x, y) for (int i = x; i < y; i++)3typedef long long ll;4using namespace std;56bool cmp(pair<int, int> a, pair<int, int> b) { return a.first + a.second < b.first + b.second; }78priority_queue<int> lpq;9priority_queue<int, vector<int>, greater<int>> rpq;10ll lsum, rsum;
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!