poj 2299 Ultra-QuickSort

点击打开poj2299

思路: 离散化+树状数组
分析:
1 题目的意思就是要求逆序数对
2 题目的输入个数有500000的规模但是每个数的最大值为999999999,因此我们需要离散化这些数据
3 对于数据9 1 0 5 4我们离散化成5 2 1 4 3
那么对于输入一个树a[i]我们去求一下它的离散化后的id,然后去求前面比这个id大的个数
4 由于getSum(x)函数的求和是求[1,x]而不是[x,MAXN),所以我们可以换成求小于等于id的个数即getSum(id),然后i-1-getSum(id)就是比id大的个数,最后在更新一下treeNum[id]

代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

const int MAXN = 500010;

int n;
int tmpNum[MAXN] , num[MAXN];
int treeNum[MAXN];

int lowbit(int x){
    return x&(-x);
}

int getSum(int x){
    int sum = 0;
    while(x){
        sum += treeNum[x]; 
        x -= lowbit(x);
    }
    return sum;
}

void add(int x , int val){
    while(x < MAXN){
         treeNum[x] += val; 
         x += lowbit(x);
    }
}

int search(int x , int len){
    int left = 1;
    int right = len;
    while(left <= right){
         int mid = (left+right)>>1; 
         if(num[mid] == x)
             return mid;
         else if(num[mid] < x)
             left = mid+1;
         else
             right = mid-1;
    }
}

long long solve(){
    long long ans = 0;
    memcpy(tmpNum , num , sizeof(num));
    memset(treeNum , 0 , sizeof(treeNum));
    sort(num+1 , num+1+n);
    int len = unique(num+1 , num+1+n)-(num+1); 
    for(int i = 1 ; i <= n ; i++){
        int id = search(tmpNum[i] , len); 
        ans += i-getSum(id)-1;
        add(id , 1);
    }
    return ans;
}

int main(){
    while(scanf("%d" , &n) && n){
         for(int i = 1 ; i <= n ; i++) 
             scanf("%d" , &num[i]);
         printf("%lld\n" , solve());
    }
    return 0;
}




你可能感兴趣的:(poj 2299 Ultra-QuickSort)