现在的位置: 首页 > 综合 > 正文

poj 2299 Ultra-QuickSort

2013年10月14日 ⁄ 综合 ⁄ 共 1951字 ⁄ 字号 评论关闭
Ultra-QuickSort
Time Limit: 7000MS   Memory Limit: 65536K
Total Submissions: 32746   Accepted: 11691

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

ps:刚学了下树状数组  所以这题用树状数组做的  不过这题正规方法应该用归并排序做的 
    各位亲们 想了解 树状数组的可以看一下 不想的就直接pass哈

#include<cstdio>
#include <cstring>
#include <algorithm>
#define maxn 500005
using namespace std;

int n;
__int64 ans;
int a[maxn];
struct Tnode
{
    int num;
    int val;
}node[maxn];

int lowbit(int v)
{
    return v&(-v);
}
void update(int v)
{
    for(int i=v; i<=maxn-5; i+=lowbit(i))
    {
        a[i]++;
    }
}
int getsum(int v)
{
    int sum=0;
    for(int i=v; i>0; i-=lowbit(i))
    {
        sum+=a[i];
    }
    return sum;
}
bool cmp1(const Tnode &x,const Tnode &y)
{
    return x.val<y.val;
}
bool cmp2(const Tnode &x,const Tnode &y)
{
    return x.num<y.num;
}
int main()
{
    int i,preval,temp;
    while(scanf("%d",&n),n)
    {
        for(i=1; i<=n; i++)
        {
            scanf("%d",&node[i].val);
            node[i].num=i;
        }
        sort(node+1,node+n+1,cmp1);
        preval=-1;
        for(i=1; i<=n; i++)         // 此循环用来离散化 a[i] 将其范围缩小到maxn内
        {                           // 注意这里不能简单地 node[i].val=i;
            temp=node[i].val;
            if(node[i].val==preval)
            {
                node[i].val=node[i-1].val;
            }
            else node[i].val=i;     
            preval=temp;

        }
        sort(node+1,node+n+1,cmp2);
        memset(a,0,sizeof(a));
        ans=0;
        for(i=1; i<=n; i++)
        {
            ans+=getsum(maxn-5)-getsum(node[i].val);
            update(node[i].val);
        }
        printf("%I64d\n",ans);   //  坑爹 原来逆序数可以很大很大 要用__int64保存  不然会WA
    }
    return 0;
}

抱歉!评论已关闭.