hdu1394 逆序数?

题目输入是n,然后输入0 ……n-1乱序,所以这题就简单了,直接找到第一个序列的逆序数sum,然后每后移一个数后的逆序数等于sum - a[i](代表该数据会产生的逆序数) + (N - a[i] - 1 );

sum - a[i] + (N - a[i] - 1);


#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>

using namespace std;

int dp[10010];
int a[10010];

int main()
{
    int N ;
    while(scanf("%d" , &N )!= EOF)
    {
        for(int i = 1 ; i <= N ; i ++ ) scanf("%d", &a[i]);
        memset(dp,0,sizeof(dp));
        for(int i = 1 ; i <= N ; i ++ )
        {
            for(int j = 1 ; j < i ; j ++ )
            {
                if(a[i] < a[j]) dp[i] ++ ;
            }
            dp[i] += dp[i-1];
        }
        int minn = dp[N];
        int sum = dp[N];
        for(int i = 1 ; i <= N ; i ++ )
        {
            sum = sum - a[i] + (N - a[i] - 1);
            if(sum < minn) minn = sum;
        }
        printf("%d\n" , minn);
    }
    return 0;
}


你可能感兴趣的:(hdu1394 逆序数?)