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(1≤n≤105,1≤m<n) - the length of the seuqence. The second line contains 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

 

思路;

假设删除的区间为 b, b左边的区间为a, b右边的区间为c。

初始时a长度为0,b的区间为1-m。

建立两个树状数组分别表示a和c的逆序对。

计算完一次后b区间向右移一位,分别计算左边增加的那个数和右边减少的那个数对a,c的逆序对影响即可。

 

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<map>
#include<algorithm>
using namespace std;
const int inf = 0x3f3f3f3f;
const int N = 100000+10;
typedef long long ll;

int n, m, a[N];
ll b[N*4], c[N*4];
int lowbit(int x)
{
    return x & (-x);
}
ll sum(ll *d, int x)
{
    int res = 0;
    while (x)
    {
        res += d[x];
        x -= lowbit(x);
    }
    return res;
}
void update(ll *d, ll x, ll v)
{
    while (x <= n)
    {
        d[x] += v;
        x += lowbit(x);
    }
}

int main()
{
    int t;
    scanf("%d", &t);
    while (t--)
    {
        int cnt = 0, ans = inf;
        scanf("%d%d", &n, &m);
        memset(b, 0, (n+3)*sizeof(ll));
        memset(c, 0, (n+3)*sizeof(ll));
        for(int i = 1; i <= n; i++)
		{
            scanf("%d", &a[i]);
		}
        for (int i = m + 1; i <= n; i++)
        {
            cnt += i - m - 1 - sum(b,a[i]);
            update(b,a[i],1);
        }
        ans = cnt;
        for (int i = m + 1; i <= n; i++)
        {
            cnt += sum(b,a[i-m]-1);
            cnt += sum(c,n) - sum(c, a[i-m]);
            update(c, a[i-m], 1);
            cnt -= sum(b, a[i]-1);
            cnt -= sum(c, n) - sum(c,a[i]);
            update(b, a[i], -1);
            ans = min(ans, cnt);
        }
        printf("%lld\n", ans);
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值