藍橋杯訓練——小朋友排隊(樹狀數組求逆序對)

題目鏈接: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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章