标签:pen iterator ios cdq分治 namespace fflush and mon har
决策单调+cdq分治。
时间复杂度为\(O(N\log^3N)\)
/*
{
######################
# Author #
# Gary #
# 2021 #
######################
*/
#include<bits/stdc++.h>
#define rb(a,b,c) for(int a=b;a<=c;++a)
#define rl(a,b,c) for(int a=b;a>=c;--a)
#define LL long long
#define IT iterator
#define PB push_back
#define II(a,b) make_pair(a,b)
#define FIR first
#define SEC second
#define FREO freopen("check.out","w",stdout)
#define rep(a,b) for(int a=0;a<b;++a)
#define SRAND mt19937 rng(chrono::steady_clock::now().time_since_epoch().count())
#define random(a) rng()%a
#define ALL(a) a.begin(),a.end()
#define POB pop_back
#define ff fflush(stdout)
#define fastio ios::sync_with_stdio(false)
#define check_min(a,b) a=min(a,b)
#define check_max(a,b) a=max(a,b)
using namespace std;
//inline int read(){
// int x=0;
// char ch=getchar();
// while(ch<‘0‘||ch>‘9‘){
// ch=getchar();
// }
// while(ch>=‘0‘&&ch<=‘9‘){
// x=(x<<1)+(x<<3)+(ch^48);
// ch=getchar();
// }
// return x;
//}
const int INF=0x3f3f3f3f;
typedef pair<int,int> mp;
/*}
*/
const int MAXN=3e5+233;
int bit[MAXN+10]={0};
int n,x;
int sum(int i){
int s=0;
while(i>0){
s+=bit[i];
i-=i&(-i);
}
return s;
}
void add(int i,int x=1){
while(i<=n){
bit[i]+=x;
i+=i&(-i);
}
}
LL dp[MAXN];
int p[MAXN];
LL tot=0;
void solve(int l,int r,int l_,int r_){
if(l>r||l_>r_) return ;
pair<LL,int> best=II(1e18,INF);
int mid=(l+r)>>1;
rb(i,l,mid){
tot+=sum(n)-sum(p[i]);
add(p[i],1);
}
// cout<<l<<‘ ‘<<r<<‘ ‘<<tot<<‘ ‘<<l_<<" "<<r_<<‘ ‘<<best.FIR<<endl;
rb(i,l_,r_){
if(i){
add(p[i],-1);
tot-=sum(p[i]);
}
check_min(best,II(dp[i]+x+tot,i));
}
// cout<<mid<<" "<<best.FIR<<endl;
rl(i,mid,l){
tot-=sum(n)-sum(p[i]);
add(p[i],-1);
}
rl(i,r_,l_){
if(i){
tot+=sum(p[i]);
add(p[i],1);
}
}
check_min(dp[mid],best.FIR);
solve(l,mid-1,l_,best.SEC);
rb(i,l_,best.SEC-1){
if(i){
add(p[i],-1);
tot-=sum(p[i]);
}
}
rb(i,l,mid){
tot+=sum(n)-sum(p[i]);
add(p[i],1);
}
solve(mid+1,r,best.SEC,r_);
rl(i,mid,l){
tot-=sum(n)-sum(p[i]);
add(p[i],-1);
}
rl(i,best.SEC-1,l_){
if(i){
tot+=sum(p[i]);
add(p[i],1);
}
}
}
void cdq(int l,int r){
if(l>=r) return ;
int mid=(l+r)>>1;
cdq(l,mid);
rl(i,mid,l){
if(i==0) continue;
tot+=sum(p[i]);
add(p[i],1);
}
// cout<<l<<‘ ‘<<mid<<endl;
// cout<<"#"<<tot<<endl;
solve(mid+1,r,l,mid);
rb(i,l,mid){
if(i==0) continue;
add(p[i],-1);
tot-=sum(p[i]);
}
// cout<<tot<<endl;
cdq(mid+1,r);
}
int main(){
memset(dp,127,sizeof(dp));
scanf("%d%d",&n,&x);
rb(i,1,n) scanf("%d",&p[i]);
dp[0]=0;
cdq(0,n);
printf("%lld\n",dp[n]);
return 0;
}
gym 102904 B Dispatch Money 题解
标签:pen iterator ios cdq分治 namespace fflush and mon har
原文地址:https://www.cnblogs.com/gary-2005/p/14422281.html