hdu5497

Inversion

Time Limit: 6000/3000 MS(Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 769    Accepted Submission(s): 215


Problem Description

You have a sequence {a1,a2,...,an} and you can delete a contiguoussubsequence of length m. So what is theminimum number of inversions after the deletion.

 

 

Input

There are multiple test cases. The first line of input contains aninteger T, indicating the number of test cases. For each testcase:

The first line contains two integers n,m(1≤n≤105,1≤m<n) - the length of the seuqence. The second linecontains n integers a1,a2,...,an(1≤ai≤n).

The sum of n in the test cases will not exceed 2×106.

 

 

Output

For each test case, output the minimum number of inversions.

 

 

Sample Input

2

3 1

1 2 3

4 2

4 1 3 2

 

 

Sample Output

0

1

 

参考链接:

官方题解

http://blog.csdn.net/one_piece_hmh/article/details/48900147

 

这道题想到了怎么算去掉某个区间后的剩下的数列的逆序数,却没有想到用树状数组算逆序数,一直想着用线段树,结果看了题解,才发现树状数组就够用了。

(感觉电脑好像出了什么问题,只是感觉,有点不对劲难过

#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
#define N 100010

int fc[N],sc[N];
int numni[N];
int tc[N];
int num[N];
int n;

int lowbit(int x){
    return ((~x)+1)&x;
    //return x&(-x);
}

int query(int *array,int x){
    int sum=0;

    while(x){
        sum+=array[x];
        x=x-lowbit(x);
    }

    return sum;
}

void add(int *array,int x,int cou){
    while(x<=n){
        array[x]+=cou;
        x=x+lowbit(x);
    }

    return;
}

int main(){
    int t;
    int m;
    long long int ans;
    long long int mni;
    long long int qumni;
    long long int allni;

    scanf("%d",&t);
    while(t--){
        scanf("%d%d",&n,&m);

        memset(fc,0,sizeof(fc));
        memset(sc,0,sizeof(sc));
        memset(tc,0,sizeof(tc));
        for(int i=1;i<=n;i++){
            scanf("%d",&num[i]);
        }

        allni=0;
        for(int i=1;i<=n;i++){
            numni[i]=query(fc,n)-query(fc,num[i]);
            allni+=numni[i];//这个原先想错了含义,放在了下一个for循环里,所以错了。
            add(fc,num[i],1);
        }
        for(int i=n;i>=1;i--){
            numni[i]+=query(sc,num[i]-1);
            //printf("%d ",numni[i]);
            add(sc,num[i],1);
        }
        //printf("\n");

        qumni=0;
        mni=0;
        for(int i=1;i<=m;i++){
            mni+=numni[i];//+=写成了=+
            qumni+=query(tc,n)-query(tc,num[i]);
            add(tc,num[i],1);
        }
        ans=mni-qumni;

        for(int i=m+1;i<=n;i++){
            mni-=numni[i-m];
            mni+=numni[i];
            qumni-=query(tc,num[i-m]-1);
            add(tc,num[i-m],-1);
            qumni+=query(tc,n)-query(tc,num[i]);
            add(tc,num[i],1);
            if(mni-qumni>ans){//这里写成了<,所以wr了
                ans=mni-qumni;
            }
        }

        //printf("%lld %lld\n",allni,ans);
        printf("%lld\n",allni-ans);
    }

    return 0;
}


posted @ 2015-10-25 17:03  buzhidaohahaha  阅读(161)  评论(0编辑  收藏  举报