题意:
N<=105的序列,求删去一个M<N的连续子序列后,剩余序列的最小逆序对数
分析:
求逆序对当然要BIT辣,然后维护删去固定大小的序列可以用two pointers
开两个BIT,b[]维护连续M子序列前面的,c[]维护后面的
删去ai+m,影响就是少了后面所有比它小的逆序对数,以及前面所有比它大的逆序对数
添加ai,同理,多了所有比它小的逆序对数,以及前面所有比它大的逆序对数
注意有重复的数哟
代码:
//
// Created by TaoSama on 2015-10-03
// Copyright (c) 2015 TaoSama. All rights reserved.
//
//#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <set>
#include <vector>
using namespace std;
#define pr(x) cout << #x << " = " << x << " "
#define prln(x) cout << #x << " = " << x << endl
const int N = 1e5 + 10, INF = 0x3f3f3f3f, MOD = 1e9 + 7;
int n, m, a[N], b[N], c[N];
void add(int *b, int i, int v) {
for(; i <= n; i += i & -i) b[i] += v;
}
int sum(int *b, int i) {
int ret = 0;
for(; i; i -= i & -i) ret += b[i];
return ret;
}
inline int read() {
int c, x;
while(c = getchar(), !isdigit(c));
x = c - '0';
while(c = getchar(), isdigit(c)) x = x * 10 + c - '0';
return x;
}
int main() {
#ifdef LOCAL
freopen("in.txt", "r", stdin);
// freopen("out.txt","w",stdout);
#endif
ios_base::sync_with_stdio(0);
int t; t = read();
while(t--) {
n = read(); m = read();
for(int i = 1; i <= n; ++i) a[i] = read();
memset(b, 0, sizeof b);
memset(c, 0, sizeof c);
long long tmp = 0;
for(int i = m + 1; i <= n; ++i) {
tmp += i - m - 1 - sum(c, a[i]);
add(c, a[i], 1);
}
long long ans = tmp;
for(int i = m + 1; i <= n; ++i) {
tmp -= sum(c, a[i] - 1);
tmp -= sum(b, n) - sum(b, a[i]);
add(c, a[i], -1);
tmp += sum(c, a[i - m] - 1);
tmp += sum(b, n) - sum(b, a[i - m]);
add(b, a[i - m], 1);
ans = min(ans, tmp);
}
printf("%I64d\n", ans);
}
return 0;
}