2299

本文介绍了一种使用树状数组实现的数据结构及其在归并排序中的应用。通过离散化处理,优化了对大量数据的操作效率。文章提供了一个具体的代码示例,展示了如何利用树状数组进行数据的更新和求和操作。
/*
树状数组,归并排序
*/

// include file
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cctype>
#include <ctime>

#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <bitset>

#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <list>
#include <functional>

using namespace std;

// typedef
typedef long long LL;
typedef unsigned long long ULL;

// 
#define read freopen("in.txt","r",stdin)
#define write freopen("out.txt","w",stdout)
#define FORi(a,b,c) for(int i=(a);i<(b);i+=c)
#define FORj(a,b,c) for(int j=(a);j<(b);j+=c)
#define FORk(a,b,c) for(int k=(a);k<(b);k+=c)
#define FORp(a,b,c) for(int p=(a);p<(b);p+=c)
#define FORii(a,b,c) for(int ii=(a);ii<(b);ii+=c)
#define FORjj(a,b,c) for(int jj=(a);jj<(b);jj+=c)
#define FORkk(a,b,c) for(int kk=(a);kk<(b);kk+=c)

#define FF(i,a)    for(int i=0;i<(a);i++)
#define FFD(i,a)   for(int i=(a)-1;i>=0;i--)

#define Z(a) (a<<1)
#define Y(a) (a>>1)

const double eps = 1e-6;
const double INFf = 1e100;
const int INFi = 1000000000;
const LL INFll = (LL)1<<62;
const double Pi = acos(-1.0);

template<class T> inline T sqr(T a){return a*a;}
template<class T> inline T TMAX(T x,T y)
{
	if(x>y) return x;
	return y;
}
template<class T> inline T TMIN(T x,T y)
{
	if(x<y) return x;
	return y;
}
template<class T> inline void SWAP(T &x,T &y)
{
	T t = x;
	x = y;
	y = t;
}
template<class T> inline T MMAX(T x,T y,T z)
{
	return TMAX(TMAX(x,y),z);
}
template<class T> inline T MMIN(T x,T y,T z)
{
	return TMIN(TMIN(x,y),z);
}


// code begin
// 最多50万个,离散化先
int N;
struct node
{
	int v;
	int dx;
	friend bool operator<(node a,node b)
	{
		return a.v<b.v;
	}
};
node D[500010];
int Ndx[500010],Nx;
LL Bit[500010];
// 是对数值进行索引
inline int lowBit(int x)
{
	return x&(-x);
}

void update(int x,int c)
{
	for(int i=x;i>0;i-=lowBit(i))
	{
		Bit[i]+=c;
	}
}
LL getSum(int x)
{
	LL ans = 0;
	for(int i=x;i<Nx;i+=lowBit(i))
	{
		ans += Bit[i];
	}
	return ans;
}
int main()
{
	read;
	write;
	while(scanf("%d",&N)==1)
	{
		if(N==0) break;
		FORi(0,N,1)
		{
			scanf("%d",&D[i].v);
			D[i].dx = i;
		}
		sort(D,D+N);
		Nx = 1; // 其实就是离散化后的数值
		Ndx[D[0].dx] = Nx++;	
		FORi(1,N,1)
		{
			if(D[i].v==D[i-1].v)
				Ndx[D[i].dx] = Nx;
			else
				Ndx[D[i].dx] = Nx++;
			//保证离散后,原来相等还是相等
		}
		//离散化后
		LL ans = 0;
		memset(Bit,0,sizeof(Bit));
		FORi(0,N,1)
		{
			// Ndx[i],离散后的编号在第i的数值
			ans += getSum(Ndx[i]);
			update(Ndx[i],1);
		}
		printf("%lld\n",ans);
	}
	return 0;
}

转载于:https://www.cnblogs.com/ac2012/archive/2011/04/12/2014155.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值