poj 2299 Ultra-QuickSort(树状数组)

本文介绍了一种特定的排序算法Ultra-QuickSort,并详细分析了其工作原理及实现方式。通过计算输入序列中元素交换次数来确定排序所需的最小操作数。采用树状数组进行逆序对计算,优化了算法效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Ultra-QuickSort
Time Limit: 7000MS Memory Limit: 65536K
Total Submissions: 67681 Accepted: 25345

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

思路;
树状数组裸题,逆序对思想,离散化处理
每插入一个点,查询下在这个点之前还有多少个点没被插入,这些点的数量就是逆序对的数量,也就是需要移动的步数
当然也可以用线段树写,只不过要多敲点。。
实现代码:
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
using namespace std;
#define ll long long
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define mid int m = (l + r) >> 1
const int M = 5e5 + 10;
const double EPS = 1e-8;
//inline int sgn(double x) return (x > EPS) - (x < -EPS); //浮点数比较常数优化写法
int b[M],c[M],n;

int lowbit(int x){
    return x&(-x);
}

int getsum(int x){
    int sum = 0;
    while(x>0){
        sum += c[x];
        x -= lowbit(x);
    }
    return sum;
}

void update(int x,int value){
    while(x<=n){
        c[x] += value;
        x += lowbit(x);
    }
}

struct node{
    int id,val;
}a[M];

bool cmp(node x,node y){
    return x.val < y.val;
}

int main()
{
    while(scanf("%d",&n)&&n){
        memset(c,0,sizeof(c));
        for(int i = 1;i <= n;i ++){
            scanf("%d",&a[i].val);
            a[i].id = i;
        }
        sort(a+1,a+n+1,cmp);
        for(int i = 1;i <= n;i ++)
            b[a[i].id] = i;
        ll ans = 0;
        for(int i = 1;i <= n;i ++){
            update(b[i],1);
            ans += i-getsum(b[i]);
        }
        cout<<ans<<endl;
    }
    return 0;
}

 



转载于:https://www.cnblogs.com/kls123/p/8977292.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值