给n个数字(0到n-1无重复),可以拿前面任意m个放到末尾。求拿多少个数字放到末尾后数列的逆序数最小。
逆序列个数是n个,如果把a[1]放到a[n]后面,逆序列个数会减少a[1]个,相应会增加n-(a[1]+1)个
比如说:
序列 3 6 9 0 8 5 7 4 2 1 把3移到后面,则它的逆序数会减少3个(0 2 1) 但同时会增加 n - a[i] - 1个。
AC代码
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int N = 5*1e3 + 10;
int C[N], n, a[N];
int lowbit(int x) {
return x & (-x);
}
int query(int x) {
int ret = 0;
while(x) {
ret += C[x];
x -= lowbit(x);
}
return ret;
}
void add(int x,int d) {
while(x <= n) {
C[x] += d;
x += lowbit(x);
}
}
int main() {
while(scanf("%d", &n) != EOF) {
memset(C, 0, sizeof(C));
ll sum = 0;
for(int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
add(a[i]+1, 1);
sum += (a[i]+1 - query(a[i]+1));
}
ll ans = INF;
for(int i = 1; i < n; i++) {
sum = sum + (n-a[i]-1) - a[i];
ans = min(ans, sum);
}
printf("%lld\n", ans);
}
return 0;
}
线段树方法求解:求解逆序数是没考虑清楚,将区间{a[i]+2, n},错写成 {a[i]+1, n},要吸取教训。
AC代码
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
using namespace std;
typedef long long ll;
const ll INF = 1e18;
const int N = 5e3 + 10;
int a[N];
ll sum[N<<2];
void build(int o, int L, int R) {
if(L == R) {
sum[o] = a[L];
return ;
}
int M = L + (R - L) / 2;
build(o*2, L, M);
build(o*2, M+1, R);
sum[o] = sum[o*2] + sum[o*2+1];
}
int ql, qr;
int query(int o, int L, int R) {
int M = L + (R - L) / 2, ans = 0;
if(ql <= L && R <= qr) return sum[o];
if(ql <= M) ans += query(o*2, L, M);
if(M < qr) ans += query(o*2+1, M+1, R);
return ans;
}
int p, v;
void modify(int o, int L, int R) {
int M = L + (R - L) / 2;
if(L == R) {
sum[o] = v;
}else {
if(p <= M) modify(o*2, L, M);
else modify(o*2+1, M+1, R);
sum[o] = sum[o*2] + sum[o*2+1];
}
}
int main() {
int n;
while(scanf("%d", &n) != EOF) {
memset(sum, 0, sizeof(sum));
build(1, 1, n);
ll ans = 0;
for(int i = 0; i < n; i++) {
scanf("%d", &a[i]);
p = a[i]+1, v = 1;
modify(1, 1, n);
ql = a[i]+2, qr = n;
ans += query(1, 1, n);
}
ll Min = ans;
for(int i = 0; i < n; i++) {
ans = ans + (n-a[i]-1) - a[i];
Min = min(Min, ans);
}
printf("%lld\n", Min);
}
return 0;
}