HDu 2686 Sort is (树状数组)

来源:互联网 发布:江西理工大学软件学院 编辑:程序博客网 时间:2024/05/21 12:40
 

Sort it

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4744    Accepted Submission(s): 3301


Problem Description
You want to processe a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. Then how many times it need.
For example, 1 2 3 5 4, we only need one operation : swap 5 and 4.
 

Input
The input consists of a number of test cases. Each case consists of two lines: the first line contains a positive integer n (n <= 1000); the next line contains a permutation of the n integers from 1 to n.
 

Output
For each case, output the minimum times need to sort it in ascending order on a single line.
 

Sample Input
31 2 34 4 3 2 1
 

Sample Output
06
他们有的用冒泡排序水过这道题,这道题的正解是用树状数组,然后求逆序数。
树状数组入门博客:http://blog.csdn.net/passer__/article/details/76653144
题意:通过多少次可以将给的数字变成从小到大的序列。
#include<stdio.h>//逆序数 #include<string.h>int a[1050];//刷新数字 int c[1050];//储存有当前这个数字前边有多少比他大的的数字 int  lowbit(int x)//树状 {    return x&(-x);}void sum1(int x,int y){    int sum=0;    while(x>0)    {        sum=sum+a[x];        x=x-lowbit(x);    }    c[y]=y-1-sum;//除去自己 用已经放进去的数字减去他前边有多少比他小的数字 就是前边有多少比它大的数字}void sum(int x) {    while(x<=1010)    {        a[x]++;        x=x+lowbit(x);    }} int main(){    int n,x;    while(scanf("%d",&n)!=EOF)    {        memset(a,0,sizeof(a));        for(int i=1;i<=n;i++)        {             scanf("%d",&x);            sum1(x,i);//查找当前数字前有多少比他小的            sum(x);        }        int sum=0;        for(int i=1;i<=n;i++)            sum=sum+c[i];        printf("%d\n",sum);        }    return 0;}