题解:P14186 [USACO08MAR] Land Acquisition G(数据加强版)
\mathcal{O}(n^2) 做法
首先考虑怎么合并一定是更优的,显然,当
可以先按
此时,若
参考代码:
sort(a + 1, a + 1 + n);
lst.push_back({0, V});
for(int i = 1; i <= n; i++){
while(a[i].y >= lst.back().y) lst.pop_back();
lst.push_back(a[i]);
}
然后观察这个折线图:
假设要选红色点和蓝色点,那么最大的
\mathcal{O}(n) 做法
可以发现,
差不多是这个样子,于是考虑从斜率的角度推一下式子:
假设
于是就可以看出这个斜率确实是单调的,就可以斜率优化了。
我们来看两种情况:
这种情况很明显三条线都可以用上,所以可以直接在后面用
这种情况绿色的线段是用不到的,所以在插入红色线段之前把这个线段排除即可。
时间复杂度
:::success[参考代码]
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
typedef long long ll;
typedef long double ld;
const int N = 2e5 + 10, V = 1e6+1;
int n; ll f[N];
struct pii{
ll x, y;
bool operator < (const pii & o) const{
return x < o.x;
}
} a[N]; vector<pii> lst;
deque<pii> q;
ld get_k(ll ax, ll ay, ll bx, ll by){
return (ld)(ay - by) / (ax - bx);
}
int main(){
cin >> n;
for(int i = 1; i <= n; i++){
cin >> a[i].x >> a[i].y;
}
sort(a + 1, a + 1 + n);
lst.push_back({0, V});
for(int i = 1; i <= n; i++){
while(a[i].y >= lst.back().y) lst.pop_back();
lst.push_back(a[i]);
}
for(int i = 1; i < lst.size(); i++){
while(q.size() >= 2){
pii tp = q.back();
q.pop_back();
if(get_k(tp.x, tp.y, q.back().x, q.back().y) > get_k(lst[i].y, f[i-1], tp.x, tp.y)){
q.push_back(tp);
break;
}
}
q.push_back((pii){lst[i].y, f[i-1]});
while(q.size() >= 2){
pii tp = q.front();
q.pop_front();
if(get_k(q.front().x, q.front().y, tp.x, tp.y) <= -lst[i].x){
q.push_front(tp);
break;
}
}
f[i] = q.front().y + (ll)lst[i].x * q.front().x;
cout << f[lst.size()-1] << '\n';
return 0;
}
:::