JOISC 2014 Day1 T2「たのしい家庭菜園」题解

题面

在这里插入图片描述

样例
6
2
8
4
5
3
6
3
分析

思路见注释

Code
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <climits>
#define LL long long
using namespace std;
const int MAXN = 3e5 + 5;
void read(int &x) {
	x = 0; int f = 1; char c = getchar();
	for(; c < '0' || c > '9'; c = getchar()) if(c == '-') f = 0;
	for(; c >= '0' && c <= '9'; c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
	x = f ? x : -x;
}
int n, a[MAXN], lsh[MAXN];
LL Bit[MAXN], tmp[MAXN], ans[MAXN], res = 0;
int Lowbit(int x) { return x & (-x); }
void Update(int x) { for(int i = x; i <= 300001; i += Lowbit(i)) Bit[i] ++; }
LL ask(int x) { LL sum_ = 0; for(int i = x; i; i -= Lowbit(i)) sum_ += Bit[i]; return sum_; }
LL Min(LL x, LL y) { return x < y ? x : y; }
// ~~容易~~发现一个性质:最小的一定要放在两边
// 我们放完最小的,就可以把第二小的当做最小的
// 那最小的放在哪边呢,显然是离他最近的那边(因为移完后其他的草相对位置不变)
// 所以对于一棵草,他的贡献为 min(左边比它大的个数,右边比他大的个数) 
int main() {
	read(n);
	for(int i = 1; i <= n; i ++) read(a[i]), ans[i] = 9e18, lsh[i] = a[i];
	sort(lsh + 1, lsh + 1 + n);
	int len = unique(lsh + 1, lsh + 1 + n) - lsh - 1;
	for(int i = 1; i <= n; i ++) a[i] = lower_bound(lsh + 1, lsh + 1 + len, a[i]) - lsh;
	for(int i = 1; i <= n; i ++) {
		ans[i] = Min(ans[i], i - 1 - ask(a[i])); Update(a[i]);
	}
	memset(Bit, 0, sizeof(Bit));
	for(int i = n; i >= 1; i --) {
		ans[i] = Min(ans[i], n - i - ask(a[i])); Update(a[i]);
	}
	for(int i = 1; i <= n; i ++) res += ans[i];
	printf("%lld", res);
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值