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.
- 题目给出n个数,问你将他排为有序的序列需要多少次交换。
- 思路,线段树和树状数组都可求解,其实在求逆序对的问题上树状数组显得更加简洁,但是个人觉得线段树也有必要掌握。题目给出的数很大,但是数据量是线段树可以接受的。离散化一下,然后借助lower_bound函数求出所在位置,我本来是用一个数组记录每个数排序完成之后的对应位置,但是超时了。还有就是最后结果会超int,所以用long long。
—暂时先写个线段树的,接下来搞一下树状数组,更新ing
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAX_SIZE = 5e5+5;
typedef long long LL;
int num[MAX_SIZE], rest[MAX_SIZE];
LL sum[MAX_SIZE<<2];
inline void Push_Up(int Root)
{
sum[Root] = sum[Root<<1] + sum[Root<<1|1];
}
void Build(int left, int right, int Root)
{
sum[Root] = 0;
if(left == right) return ;
int mid = (left+right)>>1;
Build(left, mid, Root<<1);
Build(mid+1, right, Root<<1|1);
return ;
}
void Point_Update(int pos, int left, int right, int Root)
{
if(left == right)
{
sum[Root] += 1;
return ;
}
int mid = (left+right)>>1;
if(pos <= mid) Point_Update(pos, left, mid, Root<<1);
else Point_Update(pos, mid+1, right, Root<<1|1);
Push_Up(Root);
return ;
}
LL Section_Query(int Left, int Right, int left, int right, int Root)
{
if(Left <= left && right <= Right) return sum[Root];
int mid = (left+right)>>1;
LL ans = 0;
if(Left <= mid) ans += Section_Query(Left, Right, left, mid, Root<<1);
if(Right > mid) ans += Section_Query(Left, Right, mid+1, right, Root<<1|1);
return ans;
}
int main()
{
int n;
while(scanf("%d", &n), n)
{
for(int i = 1; i <= n; i++)
{
scanf("%d", &num[i]);
rest[i] = num[i];
}
sort(rest+1, rest+1+n);
int Point_Num = unique(rest+1, rest+1+n) - (rest+1);
//for(int i = 1; i <= Point_Num; i++) _rank[rest[i]] = i;
Build(1, Point_Num, 1);
LL ans = 0;
for(int i = 1; i <= n; i++)
{
int pos = lower_bound(rest+1, rest+1+Point_Num, num[i]) - rest;
ans += Section_Query(pos+1, Point_Num, 1, Point_Num, 1);
Point_Update(pos, 1, Point_Num, 1);
}
printf("%lld\n", ans);
}
return 0;
}