最近学习斜率优化!然而其实并不明白斜率是如何操作的……还好有小天使带我❤~而且斜率优化好像是有模板的样子,很多题都可以套用模板。
基本的dp方程:
dp[i]=min(dp[j]+land.x[i]*land.y[j+1]);
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct Node {
double x, y;
}land[50005], temp[50005];
long long dp[50005];
int queue[50005], n, head = 0, tail = 1, num = 0;
bool cmp(const Node &a, const Node &b) {
return a.x > b.x;
}
double getx(int k, int j) {
return dp[k] - dp[j];
}
double gety(int k, int j) {
return land[j + 1].x - land[k + 1].x;
}
int main() {
scanf("%d", &n);
for(int i = 1; i <= n; i++)
scanf("%lf%lf", &temp[i].x, &temp[i].y);
sort(temp + 1, temp + n + 1, cmp);
land[1].y = -1.0;
for(int i = 1; i <= n; i++)
if(temp[i].y > land[num].y) {
num++;
land[num].x = temp[i].x;
land[num].y = temp[i].y;
}
for(int i = 1; i <= num; i++) {
while(head + 1 < tail && getx(queue[head + 1], queue[head]) <= land[i].y * gety(queue[head + 1], queue[head]))
head++;
dp[i] = dp[queue[head]] + land[i].y * land[queue[head] + 1].x;
while(head + 1 < tail && getx(i, queue[tail - 1])*gety(queue[tail - 1], queue[tail - 2]) <= getx(queue[tail - 1], queue[tail - 2]) * gety(i, queue[tail - 1]))
tail--;
queue[tail++] = i;
}
printf("%lld\n", dp[num]);
return 0;
}