简要题意
略
思路
首先有一个 \(O(nk)\) 的暴力dp,30pts
我们可以发扬人类智慧,构造势能函数 \(U_x=\sum_{未选择的点i}dis(i,x)+h_i\),当前在\(x\)点
定义\(f_i\)表示走到\(i\)点时势能函数的最小值,\(s_i\)表示\(i\)到起点的距离
容易发现只会跨过起点进行转移,于是 \(f_i=f_j+2\times (n-i或i-1)\times (s_i+s_j)\)
容易得到,\(f_i\)随着起点向两边递增,于是我们可以用两个指针维护两边当前还未更新的\(f_x,f_y\),每次选出小的去更新另一边,然后把指针向外移
再然后我们发现,dp柿子可以用斜率优化,这样我们就只用维护左右两边的凸包即可,正好斜率单调递增,复杂度\(O(n)\)
code
#include<bits/stdc++.h>
using namespace std;
#define N 300005
#define int long long
#define i8 __int128
int n,m,sum,d,h1=1,h2=1,t1,t2;
int s[N],f[N],q1[N],q2[N],pos[N];
int X1(int i){return -2*(n-i);}
int Y1(int i){return 2*(n-i)*s[i]+f[i];}
int xi1(int a,int b,int c){
return (i8)(Y1(a)-Y1(b))*(X1(b)-X1(c))<(i8)(Y1(b)-Y1(c))*(X1(a)-X1(b));
}
int da1(int k,int a,int b){
return (i8)k*(X1(b)-X1(a))>(Y1(b)-Y1(a));
}
void ins1(int i){
while(t1>h1&&xi1(i,q1[t1],q1[t1-1])) t1--;
q1[++t1]=i;
}
int f1(int i){
while(h1<t1&&da1(s[i],q1[h1],q1[h1+1])) h1++;
f[i]=min(f[i],Y1(q1[h1])-s[i]*X1(q1[h1]));
return Y1(q1[h1])-s[i]*X1(q1[h1]);
}
int X2(int i){return -2*(i-1);}
int Y2(int i){return 2*(i-1)*s[i]+f[i];}
int xi2(int a,int b,int c){
return (i8)(Y2(a)-Y2(b))*(X2(b)-X2(c))<(i8)(Y2(b)-Y2(c))*(X2(a)-X2(b));
}
int da2(int k,int a,int b){
return (i8)k*(X2(b)-X2(a))>(Y2(b)-Y2(a));
}
void ins2(int i){
while(t2>h2&&xi2(i,q2[t2],q2[t2-1])) t2--;
q2[++t2]=i;
}
int f2(int i){
while(h2<t2&&da2(s[i],q2[h2],q2[h2+1])) h2++;
f[i]=min(f[i],Y2(q2[h2])-s[i]*X2(q2[h2]));
return Y2(q2[h2])-s[i]*X2(q2[h2]);
}
signed main(){
freopen("cut.in","r",stdin);
freopen("cut.out","w",stdout);
scanf("%lld%lld",&n,&m);
for(int i=1;i<n;i++){
scanf("%lld",&d),pos[i+1]=pos[i]+d;
}
for(int i=1;i<=m;i++) s[i]=pos[m]-pos[i],sum+=s[i];
for(int i=m+1;i<=n;i++) s[i]=pos[i]-pos[m],sum+=s[i];
int p1,p2;p1=p2=m;
memset(f,127,sizeof(f));f[m]=sum;
ins1(p2),ins2(p1),p1--,p2++;
while(p1>=1&&p2<=n){
if(f1(p1)==f2(p2)) ins1(p2),ins2(p1),p1--,p2++;
else if(f1(p1)<f2(p2)) ins2(p1),p1--;
else ins1(p2),p2++;
}
printf("%lld\n",min(f[1],f[n]));
return 0;
}
标签:q1,2024.1,q2,21,int,题解,t2,t1,Y1
From: https://www.cnblogs.com/hubingshan/p/17978401