您的位置:首页 > 产品设计 > UI/UE

poj 2299 Ultra-QuickSort (树状数组)

2014-03-29 13:49 483 查看
Ultra-QuickSort

Time Limit: 7000MSMemory Limit: 65536K
Total Submissions: 37971Accepted: 13672
Description


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

Source

Waterloo local 2005.02.05

//Accepted    9356K    563MS    C++    1145B
/*

题意:
给出一串数列,问用冒泡排序发要进行多少次交换。

树状数组:
我的理解是这题和poj 2352类似,不过这题一定要加上离散化。

这题就是要求每个元素中排在其前面且比它大的元素的数量的和。
我转换成和之前那题一样的思想,由最大的数减去该数的排位,
最后求出来的a[i]就是所求,表示前面有i个比它大的数。然后每个
数都要交换i次,故要乘上i。

*/
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#define N 500005
using namespace std;
struct node{
int val;
int pos;
};
node no
;
int b
,a
,c
;
int cmp(const void*a,const void*b)
{
return (*(node*)a).val-(*(node*)b).val;
}
inline int lowbit(int i)
{
return i&(-i);
}
void update(int k,int detal)
{
for(;k<N;k+=lowbit(k))
c[k]+=detal;
}
inline int getsum(int k)
{
int t=0;
for(;k>0;k-=lowbit(k))
t+=c[k];
return t;
}
int main(void)
{
int n;
while(scanf("%d",&n)!=EOF && n)
{
__int64 sum=0;
for(int i=0;i<n;i++){
scanf("%d",&no[i].val);
no[i].pos=i;
}
qsort(no,n,sizeof(no[0]),cmp);
for(int i=0;i<n;i++) b[no[i].pos]=i;
//for(int i=0;i<n;i++) printf("%d\n",b[i]);
memset(c,0,sizeof(c));
memset(a,0,sizeof(a));
for(int i=0;i<n;i++){
int t=N-b[i]-5;
a[getsum(t)]++;
update(t,1);
}
for(int i=1;i<n;i++) sum+=i*a[i];
printf("%I64d\n",sum);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: