poj 2299 Ultra-QuickSort 【线段树求和(点更新)】

来源:互联网 发布:淘宝网女士纱巾 编辑:程序博客网 时间:2024/04/28 00:00
Ultra-QuickSort
Time Limit: 7000MS Memory Limit: 65536KTotal Submissions: 50810 Accepted: 18618

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

59105431230

Sample Output

60

Source

Waterloo local 2005.02.05

思路:

           先将需要排序的数输入,然后用sort 进行排序(从大到小),然后将第一个数对应的位置标记为1,然后在这个数的前面的位置找看有没有为1的数,如果有的话,就加到ans 上;然后这个数前面的区间对应的数组的值(也就是使包含这个数的区间都加1),
遍历完之后,ans保存的就是你需要找的值了!

代码:

#include <stdio.h>#include <string.h>#include <algorithm>#define MAX 500000+10typedef long long ll;using namespace std;struct node{int val,pos;}a[MAX];int sum[MAX<<2];int cmp(node a,node b){return a.val>b.val;}void build(int o,int l,int r){sum[o]=0;if(l==r)return;int mid=(l+r)>>1;build(o<<1,l,mid);build(o<<1|1,mid+1,r);}void updata(int o,int l,int r,int L){sum[o]+=1;if(l==r)return;int mid=(l+r)>>1;if(L<=mid)updata(o<<1,l,mid,L);elseupdata(o<<1|1,mid+1,r,L);}int query(int o,int l,int r,int L,int R){if(L == l && R == r){return sum[o];}int mid = (l+r) >> 1;if(R <= mid){ return query(o<<1,l,mid,L,R);}else if(L > mid){return query(o<<1|1,mid+1,r,L,R);}else{return query(o<<1,l,mid,L,mid)+query(o<<1|1,mid+1,r,mid+1,R);}}int main(){int n;while(scanf("%d",&n),n){for(int i=0;i<n;i++){scanf("%d",&a[i].val);a[i].pos=i+1;}build(1,1,n);sort(a,a+n,cmp);ll ans=0;for(int i=0;i<n;i++){updata(1,1,n,a[i].pos);if(a[i].pos==1)continue;ans+=query(1,1,n,1,a[i].pos-1);}printf("%lld\n",ans);}return 0;}


0 0
原创粉丝点击