hdu5497 Inversion

Problem Description
You have a sequence {a1,a2,...,an} and you can delete a contiguous subsequence of length m. So what is the minimum number of inversions after the deletion.
 

Input
There are multiple test cases. The first line of input contains an integer T, indicating the number of test cases. For each test case:

The first line contains two integers n,m(1n105,1m<n) - the length of the seuqence. The second line contains n integers a1,a2,...,an(1ain).

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

这场bc的题解虽然很难懂,但是弄明白后觉得写的很好。

g_igi表示在ii前面比a_iai大的数的个数, f_ifi表示在ii后面比a_iai小的数的个数, 这两个都可以用树状数组轻松求出来. 那么对于一个长度LL的连续子序列, 删掉它之后逆序对减少的个数就是这段区间中g_igi的和 + 这段区间f_ifi的和 - 这段区间的逆序对个数. 求区间逆序对个数只要用一个树状数组维护就好了, 每次只是删除最左端的一个数和加入最右端的一个数, 分别统计下贡献.

这里删除一段区间而少的逆序对其实就是区间左边每个数比区间大的数的和以及区间右边比区间内部小的数的个数和,还有区间本身的逆序对。

这里用树状数组的时候要注意,不要总是更新到maxn ,更新到n就行了,不然会超时。

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<string>
#include<algorithm>
using namespace std;
#define ll long long
#define inf 0x7fffffff
#define maxn 100100
ll sum1[maxn],sum2[maxn];
ll b[maxn+10],f[maxn],g[maxn],a1[maxn],a[maxn];
int n;

ll lowbit(ll x){
    return x&(-x);
}

void update(ll pos,ll num){
    while(pos<=n){
        b[pos]+=num;pos+=lowbit(pos);
    }
}
ll getsum(ll pos){
    ll num=0;
    while(pos>0){
        num+=b[pos];pos-=lowbit(pos);
    }
    return num;
}
void clear(){
    int i;
    for(i=1;i<=n+1;i++)b[i]=0;
}

int main()
{
    int m,i,j,T,tot;
    ll ans,cnt;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&m);
        for(i=1;i<=n;i++){
            scanf("%lld",&a[i]);
        }

        clear();
        sum1[0]=sum2[n+1]=0;
        for(i=1;i<=n;i++){
            g[i]=getsum(n)-getsum(a[i]);
            update(a[i],1);
            sum1[i]=sum1[i-1]+g[i];
        }
        clear();
        for(i=n;i>=1;i--){
            f[i]=getsum(a[i]-1);
            update(a[i],1);
        }
        for(i=1;i<=n;i++)sum2[i]=sum2[i-1]+f[i];


        clear();
        cnt=ans=0;
        for(i=m;i>=1;i--){
            ans+=getsum(a[i]-1);
            update(a[i],1);
        }
        cnt=sum1[m]+sum2[m]-ans;
        for(i=2;i+m-1<=n;i++){
            ans-=getsum(a[i-1]-1);
            update(a[i-1],-1);
            ans+=getsum(n)-getsum(a[i+m-1]);
            update(a[i+m-1],1);
            if(cnt<sum1[i+m-1]-sum1[i-1]+sum2[i+m-1]-sum2[i-1]-ans){
                cnt=sum1[i+m-1]-sum1[i-1]+sum2[i+m-1]-sum2[i-1]-ans;
            }
        }
        printf("%lld
",sum2[n]-cnt);

    }
    return 0;
}


原文地址:https://www.cnblogs.com/herumw/p/9464644.html