ZOJ 1484 Minimum Inversion Number
The inversion number of a given number sequence a1, a2, …, an is the number of pairs (ai, aj) that satisfy i < j and ai > aj.
For a given sequence of numbers a1, a2, …, an, if we move the first m >= 0 numbers to the end of the seqence, we will obtain another sequence. There are totally n such sequences as the following:
a1, a2, …, an-1, an (where m = 0 - the initial seqence)
a2, a3, …, an, a1 (where m = 1)
a3, a4, …, an, a1, a2 (where m = 2)
…
an, a1, a2, …, an-1 (where m = n-1)
You are asked to write a program to find the minimum inversion number out of the above sequences.
Input
The input consists of a number of test cases. Each case consists of two lines: the first line contains a positive integer n (n <= 5000); the next line contains a permutation of the n integers from 0 to n-1.
Output
For each case, output the minimum inversion number on a single line.
Sample Input
10
1 3 6 9 0 8 5 7 4 2
Sample Output
16
权值线段树~
首先线段树下标都是从
1
1
1 开始,所以我们输入时给每个数加
1
1
1~
我们只需要统计每个数出现的次数即可,依次将最后一个数移到第一个位置,显然逆序对变化如下:
- 在最后一个位置时数 a [ i ] a[i] a[i] 的逆序对个数为 n u m 1 = n − a [ i ] num_1=n-a[i] num1=n−a[i]
- 在第一个位置时数 a [ i ] a[i] a[i] 的逆序对个数为 n u m 2 = a [ i ] − 1 num_2=a[i]-1 num2=a[i]−1
每次变化减去 n u m 1 num_1 num1 加上 n u m 2 num_2 num2 即可,AC代码如下:
#include "bits/stdc++.h"
using namespace std;
typedef long long ll;
const int N = 5e3 + 5;
int n, a[N];
class WeightedSegmentTree {
private:
vector<ll> tree, add;
public:
void init(int n) {
tree.resize(n << 2);
add.resize(n << 2);
}
void pushup(int i) {
tree[i] = tree[i << 1] + tree[i << 1 | 1];
}
void pushdown(int i, int l, int r) {
int mid = l + (r - l) / 2;
tree[i << 1] += ll(mid - l + 1) * add[i];
tree[i << 1 | 1] += ll(r - mid) * add[i];
add[i << 1] = add[i << 1 | 1] = add[i];
add[i] = 0;
}
void build(int i, int l, int r) {
add[i] = 0;
if (l == r) {
tree[i] = 0;
return;
}
int mid = l + (r - l) / 2;
build(i << 1, l, mid);
build(i << 1 | 1, mid + 1, r);
pushup(i);
}
void update(int i, int l, int r, int m, int n, ll k) {//区间加k
if (m <= l && r <= n) {
add[i] = add[i] + k;
tree[i] = tree[i] + (r - l + 1LL) * k;
return;
}
pushdown(i, l, r);
int mid = l + (r - l) / 2;
if (m <= mid) update(i << 1, l, mid, m, n, k);
if (n > mid) update(i << 1 | 1, mid + 1, r, m, n, k);
pushup(i);
}
ll query(int i, int l, int r, int m, int n) {
if (m <= l && r <= n) return tree[i];
ll ans = 0;
int mid = l + (r - l) / 2;
pushdown(i, l, r);
if (m <= mid) ans = ans + query(i << 1, l, mid, m, n);
if (n > mid) ans = ans + query(i << 1 | 1, mid + 1, r, m, n);
return ans;
}
};
int main() {
while (~scanf("%d", &n)) {
int sum = 0;
WeightedSegmentTree t = WeightedSegmentTree();
t.init(n);
t.build(1, 1, n);
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
a[i]++;
sum += t.query(1, 1, n, a[i], n);
t.update(1, 1, n, a[i], a[i], 1);
}
int ans = sum;
for (int i = n; i >= 1; i--) {
sum = sum - (n - a[i]) + (a[i] - 1);
ans = min(ans, sum);
}
printf("%d\n", ans);
}
return 0;
}