题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1394
题意:一个由0..n-1组成的序列,每次可以把队首的元素移到队尾,求形成的n个序列中最小逆序对数目。
求逆序对数。
方法就是按序列顺序逐个读取元素,每次读取都要查询当前已读取元素中大于当前元素的个数,加到sum里,最后得到的sum即为原始数列的逆序数。
这样就是每读一个就插入到线段树或者树状数组里,查询当前元素+1到n-1中有多少数就行了。
求出了原始序列的逆序对数,从第一个元素开始往后枚举递推。 每次sum减去比它小的元素的个数,加上比它大的元素的个数。保留sum的最小值。
线段树求逆序对数:
#include <bits/stdc++.h>
using namespace std;
struct node{
int l, r, m;
int val;
};
const int maxn = 5010;
node T[maxn << 2];
int a[maxn];
void pushup(int rt) {
T[rt].val = T[rt << 1].val + T[rt << 1 | 1].val;
}
void build(int begin, int end, int rt) {
T[rt].l = begin;
T[rt].r = end;
T[rt].m = (T[rt].l + T[rt].r) >> 1;
if(begin == end) {
T[rt].val = 0;
return ;
}
build(T[rt].l, T[rt].m, rt << 1);
build(T[rt].m + 1, T[rt].r, rt << 1 | 1);
pushup(rt);
}
void update(int id, int add, int rt) {
if(T[rt].l == T[rt].r) {
T[rt].val += add;
return ;
}
if(id <= T[rt].m) update(id, add, rt << 1);
else update(id, add, rt << 1 | 1);
pushup(rt);
}
int query(int L, int R, int rt) {
if(L <= T[rt].l && T[rt].r <= R) {
return T[rt].val;
}
if(R <= T[rt].m) return query(L, R, rt << 1);
else if(L > T[rt].m) return query(L, R, rt << 1 | 1);
else return query(L, T[rt].m, rt << 1) + query(T[rt].m + 1, R, rt << 1 | 1);
}
int main() {
int n;
while(~scanf("%d", &n)) {
int sum = 0;
build(0, n - 1, 1);
for(int i = 0; i < n; i++) {
scanf("%d", a + i);
sum += query(a[i], n - 1, 1); //此处写a[i] + 1也可,不过要进行特判不是最大值
update(a[i], 1, 1);
}
int ans = sum;
for(int i = 0; i < n - 1; i++) {
sum -= a[i];
sum += (n - a[i] - 1);
if(sum < ans) ans = sum;
}
printf("%d\n", ans);
}
return 0;
}