bzoj2687 交与并(贪心+dp+决策单调性+分治)

双倍经验:portal

#include 
#include 
#include 
#include 
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
#define N 1000010
inline char gc(){
    static char buf[1<<16],*S,*T;
    if(T==S){T=(S=buf)+fread(buf,1,1<<16,stdin);if(S==T) return EOF;}
    return *S++;
}
inline int read(){
    int x=0,f=1;char ch=gc();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=gc();}
    while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=gc();
    return x*f;
}
int n,m=0;ll ans=0,f[N];
struct seg{
    int l,r;
    friend bool operator<(seg a,seg b){return a.l==b.l?a.rinline ll calc(int i,int j){
    return (ll)(a[j].r-a[i].l)*(max(a[i].r-a[j].l,0));
}
inline void cdq(int l,int r,int L,int R){
    if(l>r) return;
    if(L==R){
        for(int i=l;i<=r;++i) f[i]=calc(L,i);return;
    }int mid=l+r>>1,pos=0;
    for(int i=L;i<=min(R,mid-1);++i){
        ll res=calc(i,mid);
        if(res>f[mid]) f[mid]=res,pos=i;
    }if(pos) cdq(l,mid-1,L,pos),cdq(mid+1,r,pos,R);
    else cdq(l,mid-1,L,R),cdq(mid+1,r,L,R);
}
int main(){
//  freopen("a.in","r",stdin);
    n=read();
    for(int i=1;i<=n;++i) a[i].l=read(),a[i].r=read();
    sort(a+1,a+n+1);int r=0;
    for(int i=1;i<=n;++i){
        if(a[i].r>r) a[++m]=a[i],r=a[i].r;
        else ans=max(ans,(ll)(a[i].r-a[i].l)*(a[m].r-a[m].l));
    }cdq(2,m,1,m);
    for(int i=2;i<=m;++i) ans=max(ans,f[i]);
    printf("%lld\n",ans);
    return 0;
}

你可能感兴趣的:(bzoj,贪心)