跳到正文

题解

题解:P14899 [ICPC 2018 Yokohama R] What Goes Up Must Come Down

yedalong约 2 分钟
原文
文章信息与版本

文章信息

收录
2026年1月22日
更新
2026年1月22日
篇幅
约 2 分钟
题目
P14899

版本

  1. v1当前

前置 trick:P1774 最接近神的人。

Solution

最后这个序列是单峰的。

对于每个点,最后可能放到左边的坡上或右边的坡上,如果放到左边的坡上,代价就是这个点左边的所有大于它的点的个数,右边的同理,两种情况代价取最小值后加和即可。

时间复杂度 O(nlog⁡n)O(n\log n)。

code
C++
#include <bits/stdc++.h>
using namespace std;
#define int long long
int n,a[100005],t1[100005],t2[100005],sum1[100005],sum2[100005],ans;
int lowbit(int x){return x&-x;}
void update(int x,bool f){
	if(f) while(x<=100000) t1[x]++,x+=lowbit(x);
	else while(x<=100000) t2[x]++,x+=lowbit(x);
}
int get_sum(int x,bool f){
	int res=0;
	if(f) while(x) res+=t1[x],x-=lowbit(x);
	else while(x) res+=t2[x],x-=lowbit(x);
	return res;
}
signed main(){
	ios::sync_with_stdio(0);
	cin.tie(0),cout.tie(0);
	cin>>n;
	for(int i = 1;i<=n;i++) cin>>a[i];
	for(int i = 1;i<=n;i++)
		update(a[i],1),
		sum1[i]=i-get_sum(a[i],1);
	for(int i = n;i>=1;i--)
		update(a[i],0),
		sum2[i]=(n-i+1)-get_sum(a[i],0);
	for(int i = 1;i<=n;i++)
		ans+=min(sum1[i],sum2[i]);
	cout<<ans;
	return 0;
}
原文