POJ 2299 Ultra-QuickSort 逆序对数 树状数组+离散化

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

题意:给定一个序列,求这个序列的逆序数

思路:树状数组+离散化(可参考

这个题目值得学习的便是离散化处理(数字本身不影响结果,数字的大小关系影响结果)

思想:给出一堆数字,先记录下来这些位置,然后sort排序,根据排序重新赋值。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <map>
#include <set>
#include <cmath>
using namespace std;
const int MAXN=500010;
typedef long long ll;
int c[MAXN];
int b[MAXN];
int n;
struct node
{
    int id;//序号
    int v;
}a[MAXN];
bool cmp(node a,node b)
{
    return a.v<b.v;
}
int lowbit(int x)
{
    return x&(-x);
}
void add(int i,int val)
{
    while(i<=n)
    {
        c[i]+=val;
        i+=lowbit(i);
    }
}
int sum(int i)
{
    int s=0;
    while(i>0)
    {
        s+=c[i];
        i-=lowbit(i);
    }
    return s;
}
int main()
{
    while(scanf("%d",&n),n)
    {
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i].v);
            a[i].id=i;
        }
        memset(b,0,sizeof(b));
        memset(c,0,sizeof(c));
        //离散化
        sort(a+1,a+n+1,cmp);
        //将最小的编号为1
        b[a[1].id]=1;
        for(int i=2;i<=n;i++)
        {
            if(a[i].v!=a[i-1].v)
                b[a[i].id]=i;
            else
                b[a[i].id]=b[a[i-1].id];
        }
        ll ans=0;
        //这里用的很好
        //一开始c数组都是0,然后逐渐在b[i]处加上1;
        for(int i=1;i<=n;i++)
        {
            add(b[i],1);
            ans+=sum(n)-sum(b[i]);
        }
        printf("%I64d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/deepseazbw/article/details/81116562