https://www.luogu.com.cn/record/228613498
本帖禁水。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e6+10;
int n,m,k,pos[maxn],cnt[maxn],vis[maxn],sta[maxn];
ll py[maxn],dp[maxn];
inline void check(ll mid){
int pl=1,pr=1;
py[0]=1ll*pos[0]*pos[0]-2*pos[0];
for(int i=1;i<=n;i++){
if(!vis[i]){
dp[i]=dp[i-1];
cnt[i]=cnt[i-1];
continue;
}
while(pl<pr and (py[sta[pl+1]]-py[sta[pl]])<2ll*i*(pos[sta[pl+1]]-pos[sta[pl]])) pl++;
dp[i]=py[sta[pl]]-2ll*i*pos[sta[pl]]+1ll*i*i+2*i+1+mid;
cnt[i]=cnt[sta[pl]]+1;
py[i]=dp[i]+1ll*pos[i]*pos[i]-2*pos[i]-1ll*max(0,i-pos[i]+1)*max(0,i-pos[i]+1);
while(pl<pr and (__int128)(py[sta[pr]]-py[sta[pr-1]])*(pos[i]-pos[sta[pr]])>(__int128)(py[i]-py[sta[pr]])*(pos[sta[pr]]-pos[sta[pr-1]])) pr--;
sta[++pr]=i;
}
return;
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin>>m>>n>>k;
int ro,c;
for(int i=0;i<=n;i++) pos[i]=1e9;
for(int i=1;i<=m;i++){
cin>>ro>>c;
ro++,c++;
if(ro>c) swap(ro,c);
pos[c-1]=min(pos[c-1],ro);
vis[c]=1;
}
for(int i=n;i>=1;i--) pos[i-1]=min(pos[i-1],pos[i]);
ll l=0,r=1e12,mid,res=0;
while(l<=r){
mid=(l+r)>>1;
check(mid);
if(cnt[n]<=k) res=mid,r=mid-1;
else l=mid+1;
}
check(res);
cout<<(dp[n]-k*res)<<"\n";
return 0;
}