排序(离散化+树状数组)

题目:

数据范围大,交换相邻的的树,使有序

解题说明:关键是知道,每个数交换的次数是其前面比它大的树的个数。用树状数组维护一下~

AC代码:

#include<iostream>
#include<algorithm>
#include<string.h>
#include<map> 
using namespace std;
typedef long long ll;
const int MAXN=500010;
map<int,int>mp;
int be[MAXN];
int temp[MAXN];
int c[MAXN];
int  get(int x){
	int res=0;
	for(;x<=MAXN;x+=(x&-x))res+=c[x];
	return res;
}
void modify(int x,int sum){
	for(;x;x-=(x&-x))c[x]+=sum;
}
int main(){
	int n;
	ios::sync_with_stdio(false);
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>be[i];
		temp[i]=be[i];
	}
    sort(temp,temp+n);
    int m=unique(temp,temp+n)-temp;
    for(int i=0;i<m;i++){
    	mp[temp[i]]=i+1; 
	}
	memset(c,0,sizeof(c));
	ll ans=0;
	for(int i=0;i<n;i++){
		ans+=(ll)get(mp[be[i]]);
	    modify(mp[be[i]],1);
	}
	cout<<ans<<endl;
}


猜你喜欢

转载自blog.csdn.net/zxk_hi/article/details/80246394