poj 2299 Ultra-QuickSort

求逆序对数,树状数组+离散化
#include <iostream>           //求逆序对数,树状数组+离散化,ac
#include <algorithm>
using namespace std;
int tree[500001],list[500001],n,maxn=500000;
__int64 amount;
struct node
{
__int64 val;
int id;
bool operator<(const node& z)const
{
return val<z.val;
}
}sequence[
500001];

void hash() //离散化
{
for(int i=1;i<=n;++i)
{
scanf(
"%I64d",&sequence[i].val);
sequence[i].id
=i;
}
sort(sequence
+1,sequence+n+1);
for(int i=1;i<=n;++i)
{
list[sequence[i].id]
=i;
}
}
int lowbit(int x)
{
return x&(-x);
}
void update(int x)
{
while(x<=maxn)
{
tree[x]
++;
x
+=lowbit(x);
}
}
int getsum(int x)
{
int s=0;
while(x>0)
{
s
+=tree[x];
x
-=lowbit(x);
}
return s;
}
int main()
{
while(cin>>n&&n)
{
memset(tree,
0,sizeof(tree));
amount
=0;
hash();
for(int i=1;i<=n;++i)
{
update(list[i]);
amount
+=i-getsum(list[i]);
}
printf(
"%I64d\n",amount);
}
return 0;
}

  

树状数组
#include <iostream>            //树状数组ac
#include <algorithm>
using namespace std;
int tree[500001],list[500001],n,maxn=500000;
__int64 amount;
struct node
{
__int64 val;
int id;
bool operator<(const node& z)const
{
return val<z.val;
}
}sequence[
500001];

void hash()
{
for(int i=1;i<=n;++i)
{
scanf(
"%I64d",&sequence[i].val);
sequence[i].id
=i;
}
sort(sequence
+1,sequence+n+1);
for(int i=1;i<=n;++i)
{
list[sequence[i].id]
=i;
}
}
int lowbit(int x)
{
return x&(-x);
}
void update(int x) //update和getsum,跟上面的程序相反
{
while(x>0)
{
tree[x]
++;
x
-=lowbit(x);
}
}
int getsum(int x)
{
int s=0;
while(x<=maxn)
{
s
+=tree[x];
x
+=lowbit(x);
}
return s;
}
int main()
{
while(cin>>n&&n)
{
memset(tree,
0,sizeof(tree));
amount
=0;
hash();
for(int i=1;i<=n;++i)
{
amount
+=getsum(list[i]); //也与上面的相反
update(list[i]);
}
printf(
"%I64d\n",amount);
}
return 0;
}

  

View Code
#include <iostream>        //ac,求归并排序的逆序数
using namespace std;
__int64 list[
500005],temp[500005],amount;
int n;
void merge_sort(int beg,int end)
{
if(end==beg)
return ;
int mid=(beg+end)/2;
merge_sort(beg,mid);
merge_sort(mid
+1,end);
int p=beg,q=mid+1,t=beg;
while(p<=mid||q<=end)
{
if(q>end||(p<=mid&&list[p]<list[q]))
temp[t
++]=list[p++];
else
{
temp[t
++]=list[q++];
amount
+=mid-p+1;
}
}
for(int i=beg;i<=end;++i)
{
list[i]
=temp[i];
}
}
int main()
{
while(cin>>n&&n)
{
amount
=0;
for(int i=0;i<n;++i)
scanf(
"%I64d",&list[i]);
merge_sort(
0,n-1);
printf(
"%I64d\n",amount);
}
return 0;
}

  

posted on 2011-07-22 15:01  sysu_mjc  阅读(135)  评论(0编辑  收藏  举报

导航