您的位置:首页 > 产品设计 > UI/UE

poj 2299 Ultra-QuickSort【树状数组】

2012-08-10 12:39 417 查看
求排序的数最少的交换次数。只能相邻的交换。

归并排序算法:

View Code

#include<iostream>
#include<algorithm>
#define M 500001
using namespace std;
int c[M],aa[M],n;                   //aa数组为排序后重新编号用
struct digit
{
int num,id;
} a[M];                             //num为数的大小
bool cmp(digit a,digit b)
{
return a.num<b.num;
}
int lowbit(int t)
{
return t&(t^(t-1));
}
int sum(int t)
{
int total=0;
while(t>0)
{
total+=c[t];
t-=lowbit(t);
}
return total;
}

void update(int t,int key)
{
while(t<=n)
{
c[t]+=key;
t+=lowbit(t);
}
}
int main()
{
int i,j;
long long ans;
while(scanf("%d",&n),n)
{
memset(c,0,sizeof(c));
ans=0;
for(i=1; i<=n; i++)
{
scanf("%d",&a[i].num);
a[i].id=i;
}
sort(a+1,a+n+1,cmp);
aa[a[1].id]=1;                                 //最小的数编号为1
for(i=2; i<=n; ++i)
{
if(a[a[i].id].num!=a[a[i-1].id].num)      //如果前后两个数不等,则编号为下标
aa[a[i].id]=i;
else
aa[a[i].id]=aa[a[i-1].id];            //否则编号与前一个相同
}         //for(i=1;i<=n;i++) printf("%d ",aa[i]);
for(i=1; i<=n; ++i)
{
update(aa[i],1);
ans+=(sum(n)-sum(aa[i]));                 //每次累加该数前边比它大的数的个数
}
printf("%lld\n",ans);
}
}


Ultra-QuickSort
Time Limit: 7000MS Memory Limit: 65536K
Total Submissions: 27681 Accepted: 9924
Description

In this problem, you have to analyze a particular sorting algorithm. The algorithm processes a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. For the input sequence
9 1 0 5 4 ,

Ultra-QuickSort produces the output
0 1 4 5 9 .

Your task is to determine how many swap operations Ultra-QuickSort needs to perform in order to sort a given input sequence.
Input

The input contains several test cases. Every test case begins with a line that contains a single integer n < 500,000 -- the length of the input sequence. Each of the the following n lines contains a single integer 0 ≤ a[i] ≤ 999,999,999, the i-th input sequence element. Input is terminated by a sequence of length n = 0. This sequence must not be processed.
Output

For every input sequence, your program prints a single line containing an integer number op, the minimum number of swap operations necessary to sort the given input sequence.
Sample Input

5
9
1
0
5
4
3
1
2
3
0
Sample Output

6
0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: