链接:http://poj.org/problem?id=2299
题目: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.
题意:个一串数字,用冒泡法排序,问一共要交换多少次。
分析:数据量中等,如果用冒泡肯定会超时。一般思想,一样是排序,其实结果是在找逆序对,因为冒泡是要一个一个交换的,所以所有的逆序对都需要交换一次。所以用归并排序,在排序的时候记录一下。另一种思路是用树状数组,按顺序一个一个放到树状数组里,每放一个,所有比他大的数的个数就是与他有关的逆序对的个数。
题目: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
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.
题意:个一串数字,用冒泡法排序,问一共要交换多少次。
分析:数据量中等,如果用冒泡肯定会超时。一般思想,一样是排序,其实结果是在找逆序对,因为冒泡是要一个一个交换的,所以所有的逆序对都需要交换一次。所以用归并排序,在排序的时候记录一下。另一种思路是用树状数组,按顺序一个一个放到树状数组里,每放一个,所有比他大的数的个数就是与他有关的逆序对的个数。
题解:
由于数据比较分散,离散化了一下。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <string>
#include <cstring>
#include <functional>
#include <cmath>
#include <cctype>
#include <cfloat>
#include <climits>
#include <complex>
#include <deque>
#include <list>
#include <set>
#include <utility>
using namespace std;
__int64 ans;
int num[500010];
int bit[500010];
pair<int,int> ps[500010];
int n;
void add(int x)
{
while(x<=n){
bit[x]+=1;
x+=x&-x;
}
}
__int64 countn(int x)
{
__int64 an=0;
while(x){
an+=bit[x];
x-=x&-x;
}
return an;
}
int main()
{
//freopen("in.txt","r",stdin);
while(~scanf("%d",&n)&&n)
{
memset(bit,0,sizeof bit);
ans=0;
for(int i=1;i<=n;i++){
cin>>ps[i].first;
ps[i].second=i;
}
sort(ps+1,ps+n+1);
num[ps[1].second]=1;
for(int i=2;i<=n;i++){
if(ps[i].second==ps[i-1].second)
num[ps[i].second]=num[ps[i-1].second];
else
num[ps[i].second]=i;
}
for(int i=1;i<=n;i++){
ans+=countn(n)-countn(num[i]);
add(num[i]);
}
printf("%I64d\n",ans);
}
return 0;
}