B - 是你吻开笔墨 POJ - 2299 Ultra-QuickSort 逆序数 树状数组+离散化

B – 是你吻开笔墨

 POJ – 2299 

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

 题意:每次只能交换相邻的两个数,问至少多少次可以变成升序。

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <vector>
#include <malloc.h>
#define Twhile() int T;scanf("%d",&T);while(T--)
#define clc(a,b,n) for(int i=0;i<=n;i++)a[i]=b
#define clc2(a,b,n,m) for(int i=0;i<=n;i++)for(int j=0;j<=m;j++)a[i][j]=b
#define fora(i,a,b) for(int i=a;i<b;i++)
#define fors(i,a,b) for(int i=a;i>b;i--)
#define fora2(i,a,b) for(int i=a;i<=b;i++)
#define fors2(i,a,b) for(int i=a;i>=b;i--)
#define PI acos(-1.0)
#define eps 1e-6
#define INF 0x3f3f3f3f
#define BASE 131
#define lowbit(x) x&(-x)

typedef long long LL;
typedef long double LD;
typedef unsigned long long ULL;
using namespace std;
const int maxn=500000+11;
int tre[maxn];
LL b[maxn],a[maxn];

void update(int i,int val,int n)//n是树的大小
{
    for(;i<=n;i+=lowbit(i))
        tre[i]+=val;
}
int sum(int i)
{
    int ret=0;
    for(;i;i-=lowbit(i))
        ret+=tre[i];
    return ret;
}
int main()
{
    int N;
    while(~scanf("%d",&N)&&N)
    {
        memset(tre,0,sizeof(tre));
        fora2(i,1,N)
        {
            scanf("%lld",a+i);
            b[i]=a[i];
        }
        sort(b+1,b+N+1);
        LL ans=0;
        fora2(i,1,N)
        {
            int k=lower_bound(b+1,b+N+1,a[i])-b;
            int tem=sum(k);
            ans+=i-tem-1;//printf("*******%d %d %d\n",k,tem,i-tem-1);
            update(k,1,maxn);
        }
        printf("%lld\n",ans);


    }
    return 0;
}

 

    原文作者:B树
    原文地址: https://blog.csdn.net/liyang__abc/article/details/81810255
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞