hdu-5497 Inversion(滑动窗口+树状数组)

本文介绍了一种解决特定问题的算法:在一个整数序列中删除长度为m的连续子序列,以使得剩余序列的逆序对数量达到最小。通过使用树状数组和滑动窗口技巧来高效计算逆序对的数量。

题目链接:

Inversion

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


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
 
题意:
有一个序列,然后你可以删除一个长度为mm的连续子序列. 问如何删除才能使逆序对最少.

思路:

也是套路,逆序对可以用树状数组求得,连续的可以使用滑动窗口,跟尺取法差不多啦;开了两个树状数组一个记录左边界之前的数,一个记录右边界后面的数,然后更新逆序对的数目,取最小就好了;

AC代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn=1e5+10;
int sum1[maxn],sum2[maxn],n,m,a[maxn];
int lowbit(int x){return x&(-x);}
inline void update1(int x,int num)
{
    while(x<=n)
    {
        sum1[x]+=num;
        x+=lowbit(x);
    }
}
inline int query1(int x)
{
    int s=0;
    while(x)
    {
        s+=sum1[x];
        x-=lowbit(x);
    }
    return s;
}
inline void update2(int x,int num)
{
    while(x<=n)
    {
        sum2[x]+=num;
        x+=lowbit(x);
    }
} 
inline int query2(int x)
{
    int s=0;
    while(x)
    {
        s+=sum2[x];
        x-=lowbit(x);
    }
    return s;
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        for(int i=0;i<=n;i++)sum1[i]=sum2[i]=0;
        for(int i=1;i<=n;i++)scanf("%d",&a[i]);
        LL su=0;
        for(int i=n;i>0;i--)
        {
            su=su+query2(a[i]-1);
            update2(a[i],1);
        }
        LL ans=su,temp=su;int l,r=1;
        for(l=1;l<=n-m+1;l++)
        {
            while(r-l<m&&r<=n)
            {
                update2(a[r],-1);
                temp=temp-query2(a[r]-1);
                temp=temp-(l-1-query1(a[r]));
                r++;
            }
            ans=min(ans,temp);
            temp=temp+(l-1-query1(a[l]));
            temp=temp+query2(a[l]-1);
            update1(a[l],1);
        }
        printf("%lld\n",ans);
    }
    return 0;
}

  

 

转载于:https://www.cnblogs.com/zhangchengc919/p/5922283.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值