HDU 5497 - Inversion (树状数组 + 序列逆序对)

Oct 8, 2015


## 题意 ##

删除一个长度为m的序列,问剩下的最小逆序对是多少。

## 思路 ##

我们考虑这个序列的贡献。

每个数分为对前面的贡献,和对后面的贡献。

所以只要统计一下,这个数后面比他小的有多少,这个数前面比他大的有多少。

当删除的区间移动的时候,维护一下减少的逆序对和增加的逆序对。

统计贡献统计贡献,感觉现在碰到每题都统计贡献了。

## 代码 ##

#include <stack>
#include <cstdio>
#include <list>
#include <cassert>
#include <set>
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <queue>
#include <functional>
#include <cstring>
#include <algorithm>
#include <cctype>
#pragma comment(linker, "/STACK:102400000,102400000")
#include <string>
#include <map>
#include <cmath>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/hash_policy.hpp>
using namespace std;
//using namespace __gnu_pbds;
#define LL long long
#define ULL unsigned long long
#define SZ(x) (int)x.size()
#define Lowbit(x) ((x) & (-x))
#define MP(a, b) make_pair(a, b)
#define MS(p, num) memset(p, num, sizeof(p))
#define PB push_back
#define X first
#define Y second
#define ROP freopen("input.txt", "r", stdin);
#define MID(a, b) (a + ((b - a) >> 1))
#define LC rt << 1, l, mid
#define RC rt << 1|1, mid + 1, r
#define LRT rt << 1
#define RRT rt << 1|1
#define FOR(i, a, b) for (int i=(a); (i) < (b); (i)++)
#define FOOR(i, a, b) for (int i = (a); (i)<=(b); (i)++)
const double PI = acos(-1.0);
const int INF = 0x3f3f3f3f;
const double eps = 1e-8;
const int MAXN = 1e5+10;
const int MOD = 100000007;
const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
const int seed = 131;
int cases = 0;
typedef std::pair<int, int> pii;
 
int bef[MAXN], aft[MAXN], arr[MAXN];
 
int query(int *C, int n)
{
    int ret = 0;
    while (n)
    {
        ret += C[n];
        n -= Lowbit(n);
    }
    return ret;
}
 
void update(int *C, int n, int val)
{
    while (n < MAXN)
    {
        C[n] += val;
        n += Lowbit(n);
    }
}
 
int n, m;
int main()
{
    //ROP;
    int T;
    scanf("%d", &T);
    while (T--)
    {
        MS(aft, 0); MS(bef, 0);
        scanf("%d%d", &n, &m);
        for (int i = 1; i <= n; i++) scanf("%d", &arr[i]);
        LL ans = 0;
        for (int i = n; i > m; i--)
        {
            ans += query(aft, arr[i]-1);
            update(aft, arr[i], 1);
        }
        LL fin = ans;
        for (int i = 1; i+m <= n; i++)
        {
            //先减去接下来一位的贡献
            ans -= query(aft, arr[i+m]-1);
            ans -= (i-1) - query(bef, arr[i+m]);        //对之前元素的贡献
            update(aft, arr[i+m], -1);
            ans += query(aft, arr[i]-1);
            ans += (i-1) - query(bef, arr[i]);
            update(bef, arr[i], 1);
            fin = min(fin, ans);
        }
        printf("%I64d\n", fin);
    }
    return 0;
}