n 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.
Ultra-QuickSort produces the output
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
逆序数对,一开始是在归并排序那了解到的,现在知道还可以用树状数组做,当然也可以用线段树(能用树状数组解决的,都能用线段树做,反过来不行)而且,后两种方法的效率要比归并排序高很多,题目数据的范围太大,树状数组那里用了离散化。直接上代码吧
//归并排序
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 5e5 + 3;
long long cnt;
void Merge(long long a[], int l, int mid, int r)
{
int b[N], i = l, j = mid + 1, k = 0;
while(i <= mid && j <= r)
{
if(a[i] <= a[j])
b[k++] = a[i++];
else
{
b[k++] = a[j++];
cnt += mid - i + 1; //注意理解这里,结合归并排序的原理
}
}
while(i <= mid) b[k++] = a[i++];
while(j <= r) b[k++] = a[j++];
for(i = 0; i < k; i++)
a[l + i] = b[i];
}
void MergeSort(long long a[], int l, int r)
{
if(l < r)
{
int mid = (l + r) >> 1;
MergeSort(a, l, mid);
MergeSort(a, mid + 1, r);
Merge(a, l, mid, r);
}
}
int main()
{
long long a[N];
int n;
while(~scanf("%d", &n) && n)
{
for(int i = 0; i < n; i++)
scanf("%lld", &a[i]);
cnt = 0;
MergeSort(a, 0, n - 1);
printf("%lld\n", cnt);
}
return 0;
}
//树状数组
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#define lowbit(x) (x & (-x))
using namespace std;
const int N = 5e5 + 3;
struct node
{
long long d;
int p;
}t[N];
int c[N], a[N];
void Update(int k)
{
for(int i = k; i < N; i += lowbit(i))
c[i]++;
}
int GetSum(int k)
{
int sum = 0;
for(int i = k; i > 0; i -= lowbit(i))
sum += c[i];
return sum;
}
bool cmp(node a, node b)
{
return a.d < b.d;
}
int main()
{
int n;
while(~scanf("%d", &n) && n)
{
memset(c, 0, sizeof(c));
for(int i = 1; i <= n; i++)
{
scanf("%lld", &t[i].d);
t[i].p = i;
}
sort(t, t + n + 1, cmp); //排序,接下来是离散化
for(int i = 1; i <= n; i++)
{
if(i == 1 || t[i].d != t[i - 1].d)
a[t[i].p] = i;
else
a[t[i].p] = a[t[i - 1].p];
}
long long cnt = 0;
for(int i = 1; i <= n; i++)
{
Update(a[i]);
cnt += i - GetSum(a[i]); //GetSum(x)得到的是x左边比它小的个数
}
printf("%lld\n", cnt);
}
return 0;
}