【逆序对】(线段树 | 离散化 | 桶记录 | 在线算法)

#include 
#include 
#include 
#include 

static int cmp(const void*a,const void*b){return *(int*)a<=*(int*)b;}
static void Discrete(int A[],int N)
{
	int *Bin = (int*)malloc(sizeof(int)*(N+1));
	register int Cnt = 0,i = 1;
	int l,r,m;
	for(;i <= N;++i)Bin[++Cnt] = A[i];
	qsort(Bin+1,N,sizeof(int)*N,cmp);
	i = Cnt = 1;
	while(++i != N+1)
	{
		if(!(Bin[i] == Bin[Cnt]) && ++Cnt != i)
		{Bin[Cnt] = Bin[i];i = Cnt;}
	}
	for(i = 1;i <= N;++i)
	{
		l = 1,r = Cnt;
		while(l+1>1);
			if(Bin[m]>1);
 	if(p<=Mid)SingMod(Segm,p,Lft,Mid,LftChild(x));
 	else SingMod(Segm,p,Mid+1,Rght,RghtChild(x));
 	Segm[x] = Segm[LftChild(x)]+Segm[RghtChild(x)];
}
static int Query(int* Segm,int Beg,int End,int x,int Lft,int Rght)
{
	if(Lft > Rght)return 0;
	if(Beg<=Lft && Rght <= End)return Segm[x];
 	int Mid = Lft+((Rght-Lft)>>1),Ret = 0;
	if(Beg <= Mid)Ret += Query(Segm,Beg,End,LftChild(x),Lft,Mid);
	if(End > Mid)Ret += Query(Segm,Beg,End,RghtChild(x),Mid+1,Rght);
	return Ret;
}
static int RevSeq(int A[],int N)
{
	int *Bin = (int*)malloc(sizeof(int)*(N+1)),
		*Segm = (int*)malloc(sizeof(int)*((N<<2)+1)),
		Cnt = 0,i = 0;
	for(i = 1;i <= N;++i)Bin[++Cnt] = A[i];
	qsort(Bin+1,N,sizeof(int)*N,cmp);
	Cnt = std::unique(Bin+1,Bin+N+1)-(Bin+1);
	for(i = 1;i <= N;++i)
		A[i] = std::lower_bound(Bin+1,Bin+N+1,A[i])-Bin;
	memset(Segm,0,sizeof(Segm));
	Cnt = 0;
	for(i = 1;i <= N;++i)
	{
		SingMod(Segm,A[i],1,N,1);
		Cnt += Query(Segm,A[i]+1,N,1,1,N);
	}
	free(Bin);
	return Cnt;
}

你可能感兴趣的:(算法,数据结构,c++,leetcode)