现在的位置: 首页 > 综合 > 正文

nyoj 322 sort(树状数组求逆序数)

2018年04月26日 ⁄ 综合 ⁄ 共 898字 ⁄ 字号 评论关闭
难度:4
描述
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.

输入
The input consists of T number of test cases.(<0T<1000) 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.
输出
For each case, output the minimum times need to sort it in ascending order on a single line.
样例输入
2
3
1 2 3
4
4 3 2 1
样例输出
0
6

 

#include<stdio.h>
#include<string.h>
int num[1004],n;
int lowbit(int x)
{
    return x&(-x);
}
void add(int x)
//更新含有x的数组个数
{
    while(x<=n)
    {
        num[x]++;
        x+=lowbit(x);
    }
}
int sum(int x)
//向下统计小于x的个数
{
    int total=0;
    while(x>0)
    {
        total+=num[x];
        x-=lowbit(x);
    }
    return total;
}
int main()
{
    int x,cases;
    scanf("%d",&cases);
    while(cases--)
    {
        scanf( "%d",&n);
        memset( num,0,sizeof( num ));
        int ss = 0;
        for( int i = 0; i < n; ++i )
        {
            scanf( "%d",&x);
            add(x);
            ss += (i-sum( x - 1 ));
        }
        printf( "%d\n",ss );
    }
    return 0;
}
        

抱歉!评论已关闭.