poj 2299 Ultra-QuickSort (tree array)

Ultra-QuickSort
Time Limit: 7000MS   Memory Limit: 65536K
Total Submissions: 67681   Accepted: 25345

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 

idea;
tree-like array bare questions, reverse order pair ideas, discretization processing
each time a point is inserted, query how many points have not been inserted before this point, the number of these points is the number of reverse order pairs, that is, the need to move Of course , the number of steps
can also be written in the line segment tree, but you need to tap more. .
Implementation code:
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
using namespace std;
#define ll long long
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define mid int m = (l + r) >> 1
const int M = 5e5 + 10;
const double EPS = 1e-8;
//inline int sgn(double x) return (x > EPS) - (x < -EPS); //浮点数比较常数优化写法
intb[M],c[M],n;

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

int getsum(int x){
    int sum = 0;
    while(x>0){
        sum += c[x];
        x -= lowbit(x);
    }
    return sum;
}

void update(int x,int value){
    while(x<=n){
        c[x] += value;
        x += lowbit(x);
    }
}

struct node{
    int id,val;
}a[M];

bool cmp(node x,node y){
    return x.val < y.val;
}

intmain ()
{
    while(scanf("%d",&n)&&n){
        memset(c,0,sizeof(c));
        for(int i = 1;i <= n;i ++){
            scanf("%d",&a[i].val);
            a[i].id = i;
        }
        sort(a+1,a+n+1,cmp);
        for(int i = 1;i <= n;i ++)
            b[a[i].id] = i;
        ll ans = 0;
        for(int i = 1;i <= n;i ++){
            update(b[i],1);
            ans += i-getsum(b[i]);
        }
        cout<<ans<<endl;
    }
    return 0;
}

 



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325101390&siteId=291194637
Recommended