一、内容
In this problem, you have to analyze a particular sorting algorithm. The algorithm processes a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. For the input sequence
9 1 0 5 4 ,
Ultra-QuickSort produces the output
0 1 4 5 9 .
Your task is to determine how many swap operations Ultra-QuickSort needs to perform in order to sort a given input sequence.
Input
The input contains several test cases. Every test case begins with a line that contains a single integer n < 500,000 -- the length of the input sequence. Each of the the following n lines contains a single integer 0 ≤ a[i] ≤ 999,999,999, the i-th input sequence element. Input is terminated by a sequence of length n = 0. This sequence must not be processed.
Output
For every input sequence, your program prints a single line containing an integer number op, the minimum number of swap operations necessary to sort the given input sequence.
Sample Input
5
9
1
0
5
4
3
1
2
3
0
Sample Output
6
0
二、思路
- 求逆序对的话,我们只需要求某个数后面有多少个小于它的数即可。 所以只需要用树状数组查询一下**[1-x-1] 这个区间**有多少数就可以了。
- 首先由于数很大,那么必须进行离散化。 于是用一个结构体存一下val(本身的值),id(原来的位置)。 然后进行排序一下,那么就可以得出离散后每个数的转化的值了。
三、代码
#include <cstdio>
#include <algorithm>
#include <cstring>
typedef long long ll;
using namespace std;
const int N = 500005;
struct Node {
ll val;
int id;
bool operator < (const Node& w) const {
return val < w.val;
}
} no[N];
int n, c[N], w[N];
void update(int x, int d) {
for (int i = x; i <= n; i += i & (-i)) c[i] += d;
}
int query(int x) {
int ans = 0;
for (int i = x; i > 0; i -= i & (-i)) ans += c[i];
return ans;
}
int main() {
while (scanf("%d", &n), n) {
memset(c, 0, sizeof(c));
for (int i = 1; i <= n; i++) {
scanf("%d", &no[i].val);
no[i].id = i; //原来的位置
}
sort(no + 1, no + 1 + n);
//更新当前w的值
for (int i = 1; i <= n; i++) {
//值就排序好了 并从1--n
w[no[i].id] = i; //那么就转化成1-n中的某个数 no[i].id是原来的位置
}
ll ans = 0; //保存答案
for (int i = n; i >= 1; i--) {
//寻找比它小的数 有多少个
ans += query(w[i] - 1);
update(w[i], 1);
}
printf("%lld\n", ans);
}
return 0;
}