1. 程式人生 > >[CF321E]Ciel and Gondolas&&[BZOJ5311]貞魚

[CF321E]Ciel and Gondolas&&[BZOJ5311]貞魚

namespace 復雜度 con || .com and clu spa php

codeforces
bzoj

description

\(n\)個人要坐\(k\)輛車。如果第\(i\)個人和第\(j\)個人同坐一輛車,就會產生\(w_{i,j}\)的代價。
求最小化代價。\(n\le4000\)

sol

凸優化+決策單調性優化
這麽一講其實這題就已經做完了,復雜度\(O(n\log n\log w)\)

code

\(bzoj\)上需要卡常。上網蒯個讀入優化模板就行了。

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int gi(){
    int x=0,w=1;char ch=getchar();
    while ((ch<'0'||ch>'9')&&ch!='-') ch=getchar();
    if (ch=='-') w=0,ch=getchar();
    while (ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
    return w?x:-x;
}
const int N = 4005;
struct node{int j,l,r;}q[N];
int n,k,s[N][N],f[N],g[N],hd,tl;
int cal(int j,int i){
    return f[j]+(s[i][i]-s[i][j]-s[j][i]+s[j][j]>>1);
}
bool better(int i,int j,int k){
    int si=cal(i,k),sj=cal(j,k);
    return si<sj||(si==sj&&g[i]<g[j]);
}
int binary(int i,int j){
    int l=q[tl].l,r=n,res=0;
    while (l<=r){
        int mid=l+r>>1;
        if (better(i,j,mid)) res=mid,r=mid-1;
        else l=mid+1;
    }
    return res;
}
void solve(int c){
    q[hd=tl=1]=(node){0,0,n};
    for (int i=1;i<=n;++i){
        ++q[hd].l;if (q[hd].l>q[hd].r) ++hd;
        f[i]=cal(q[hd].j,i)+c;g[i]=g[q[hd].j]+1;
        if (hd>tl||better(i,q[tl].j,n)){
            while (hd<=tl&&better(i,q[tl].j,q[tl].l)) --tl;
            if (hd>tl) q[++tl]=(node){i,i,n};
            else{
                int x=binary(i,q[tl].j);
                q[tl].r=x-1;q[++tl]=(node){i,x,n};
            }
        }
    }
}
int main(){
    n=gi();k=gi();
    for (int i=1;i<=n;++i)
        for (int j=1;j<=n;++j)
            s[i][j]=s[i-1][j]+s[i][j-1]-s[i-1][j-1]+gi();
    int l=0,r=s[n][n],res=0;
    while (l<=r){
        int mid=l+r>>1;solve(mid);
        if (g[n]<=k) res=mid,r=mid-1;else l=mid+1;
    }
    solve(res);printf("%d\n",f[n]-k*res);return 0;
}

[CF321E]Ciel and Gondolas&&[BZOJ5311]貞魚