蓝桥杯训练——小朋友排队(树状数组求逆序对)

题目链接:https://www.dotcpp.com/oj/problem1439.html

 假设某同学左边以后x个比他高的,右边有y个比他矮的,那么他一共交换k=x+y次。又可知不高性值和次数成一个前n项和关系。

#include <iostream>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <vector>
#include <map>
#include <queue>
#include <cstdio>
#include <string>
#include <stack>
#include <set>
#define IOS ios::sync_with_stdio(false), cin.tie(0)
using namespace std;
typedef long long ll;
ll c[1000010];
ll a[100010];
ll left_s[100010];
ll maxn=0;
ll lowbit(ll pos){
	return pos&(-pos);
}
void insert(ll pos){
	while(pos<=maxn){
		c[pos]+=1;
		pos+=lowbit(pos);
	}
}
ll getsum(ll pos){
	ll sum=0;
	while(pos>0){
		sum+=c[pos];
		pos-=lowbit(pos);
	}
	return sum;
}
int main()
{
	IOS;
	int n;
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>a[i];
		maxn=max(maxn,++a[i]);
	}
	ll right=0;
	ll ans=0;
	//求左边比其大的数个数
	memset(c,0,sizeof(c));
	for(int i=1;i<=n;i++){
		insert(a[i]);
		left_s[i]=i-getsum(a[i]);
	}
	//求右边比其小的数个数
	memset(c,0,sizeof(c));
	for(int i=n;i>0;i--){
		insert(a[i]);
		right=getsum(a[i]-1);
		ll k=right+left_s[i];//因这里k之前声明成int型,偏小了
		ans=ans+(k+1)*k/2;
	}
	cout<<ans<<endl;
	getchar();
	getchar();
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值