Poj2299(离散化)

来源:互联网 发布:新房装修 淘宝 推荐 编辑:程序博客网 时间:2024/05/16 16:58



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

题意:

将n个数按照递增顺序排列,问交换的次数。

题解:

数据代太大,得离散化,然后用树状数组套,这里不会离散化的同学,一定要在纸上推一下这个过程,真的很nice的一个技巧。

代码:

#include <stdio.h>
#include <stdlib.h>
#include <queue>
#include <algorithm>
#include <cstring>
#include <iostream>
const int maxn=500005;
int n;
using namespace std;
int aa[maxn];
int c[maxn];
struct node//用结构体记录输出数据和下标。
{
    int v;
    int order;
}in[maxn];
int lowbit(int x)
{
    return x&(-x);
}
int sum(int x)
{
    int ans=0;
    while(x>0)
    {
        ans+=c[x];
        x-=lowbit(x);
    }
    return ans;
}
int add(int x,int y)
{
    while(x<=n)
    {
        c[x]+=y;
        x+=lowbit(x);
    }
}
bool cmp(node x,node y)
{
    return x.v<y.v;
}
int main()
{
    while(cin>>n)
    {
        if(n<=0)
            break;
        for(int i=1;i<=n;i++)
        {
            cin>>in[i].v;
            in[i].order=i;
        }
        sort(in+1,in+1+n,cmp);
        for(int i=1;i<=n;i++)//离散化。
        {
            aa[in[i].order]=i;
        }
        memset(c,0,sizeof(c));
        long long ans=0;
        for(int i=1;i<=n;i++)
        {
            add(aa[i],1);
            ans+=i-sum(aa[i]);
        }
        cout<<ans<<endl;
    }
    }


0 0
原创粉丝点击