HDU 1394 Minimum Inversion Number
http://acm.hdu.edu.cn/showproblem.php?pid=1394
Problem Description
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.
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
代码:
#include <bits/stdc++.h> using namespace std; const int maxn = 5010; int N; int c[maxn], a[maxn]; int lowbit(int x) { return x & (-x); } void add(int x, int val) { while(x <= N) { c[x] += val; x += lowbit(x); } } int getsum(int x) { int sum = 0; while(x > 0) { sum += c[x]; x -= lowbit(x); } return sum; } int main() { while(~scanf("%d", &N)) { if(!N) break; memset(c, 0, sizeof(c)); int ans = 0; for(int i = 1; i <= N; i ++) { scanf("%d", &a[i]); a[i] += 1; ans += getsum(N) - getsum(a[i]); add(a[i], 1); } int minn = ans; for(int i = 1; i <= N; i ++) { ans += N - a[i] + 1 - a[i]; minn = min(minn, ans); } printf("%d\n", minn); } return 0; }
树状数组 先把 a 数组输进来的时候加一 (因为平时写的逆序数的模板都是 1 开始的 呜呜呜) 本来写了一波暴力 稳稳的 TLE 但是每次拿一个到最后然后得到的逆序数数量是有规律的
15h