Slope trick 科技
例题:https://www.luogu.com.cn/problem/CF1534G
题目的dp方程大概长这个样纸:
其实对于这一类(甚至更多)的方程,可以用 slope trick 解决。
先放一个 CF 的链接:
https://codeforces.com/blog/entry/47821
我们考虑这么做:把
然后怎么做呢?不难发现,
证明:比较显然,不再赘述。
考虑
相当于找到
中间的就用一条横线盖过。
于是我们考虑维护,相当于要支持两个操作:
- 裂开函数并平移
- 用该函数加上一个绝对值函数
不难发现,增加一个绝对值函数相当于区间
至于裂开和平移的操作,用两个变量记录一下相对位置即可。
放个代码:
#include<cstdio>
#include<queue>
#include<algorithm>
#define N 1000010
using namespace std;
priority_queue<int>L;
priority_queue<int,vector<int>,greater<int> >R;
struct node{
int x,y;
void read(){scanf("%d%d",&x,&y);}
}p[N];
bool cmp(node a,node b){return a.x+a.y<b.x+b.y;}
int n,t,x,l,r;
long long ans;
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++) p[i].read();
sort(p+1,p+n+1,cmp);
L.push(p[1].x),R.push(p[1].x);
for(int i=2;i<=n;i++)
{
t+=p[i].x+p[i].y-p[i-1].x-p[i-1].y;
x=p[i].x;
l=L.top(),r=R.top()+t;
if(x<l) L.pop(),L.push(x),R.push(l-t),L.push(x),ans+=l-x;
if(x>r) R.pop(),R.push(x-t),R.push(x-t),L.push(r),ans+=x-r;
if(l<=x&&x<=r) L.push(x),R.push(x-t);
}
printf("%lld",ans);
}