树状数组离散化(求逆序数)

本文介绍了一种名为Ultra-QuickSort的特定排序算法,并详细分析了其工作原理及实现方式。该算法通过交换相邻元素的方式对整数序列进行升序排序,并计算排序过程中所需的交换次数。

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

  Ultra-QuickSort

Time Limit: 2.0 Seconds    Memory Limit: 65536K



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.

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.

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

Output for Sample Input

6
0


Source:  Waterloo Local Contest Feb. 5, 2005

Problem ID in problemset: 1455

数的范围很大,但是只有500000个,学习了一下离散化

用一个struct存值和顺序,然后离散化的时候使用顺序就不会超过范围了。

#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
long long int c[500500];
int n;
struct s{
    int v,order;
}a[500500];
int aa[500500];
int lb(int i)
{
    return i&(-i);
}
int get(int i)
{
    int ans=0;
    while(i>0)
    {
        ans+=c[i];
        i-=lb(i);
    }
    return ans; //有时候忘记写返回值,很蠢
}
void sets(int i,int x)
{
    while(i<=n)
    {
        c[i]+=x;
        i+=lb(i);
    }
}
bool cmp(s a,s b)
{
    if(a.v<b.v)
        return 1;
    return 0;
}
int main()
{
    while(cin>>n)
    {
        memset(c,0,sizeof(c));
        long long int ans=0;
        if(n==0)
            break;
        for(int i=1;i<=n;i++)
        {
            cin>>a[i].v;
            a[i].order=i;
        }
        sort(a+1,a+n+1,cmp);
        for(int i=1;i<=n;i++)
            aa[a[i].order]=i;
        for(int i=1;i<=n;i++)
        {
            sets(aa[i],1);
            ans+=(i-get(aa[i]));
        }
        cout<<ans<<endl;
    }
    return 0;
}

### 使用树状数组(Fenwick Tree)计算逆序对 #### 方法概述 树状数组是一种支持高效单点更新和前缀和查询的数据结构,其核心思想是通过一种特殊的二进制表示方法来存储部分前缀和,从而使得每次更新或查询的时间复杂度降低至 \(O(\log n)\)[^1]。对于逆序对问题,可以通过从右向左遍历数组的方式,利用树状数组记录已经访问过的元素并统计小于当前元素的数量。 具体做法如下: - 将原数组中的数值离散化为排名值,以便减少内存占用。 - 初始化一个长度等于最大排名值的树状数组。 - 从右往左依次处理每个元素,先查询该元素之前有多少个大于它的数,再将其加入树状数组中[^2]。 --- #### 核心代码实现 (C++) 以下是基于 C++ 的树状数组实现逆序对计数的具体代码: ```cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; // 定义树状数组类 class FenwickTree { public: vector<int> tree; int size; FenwickTree(int n) : size(n), tree(n + 1, 0) {} // 更新某个位置的值 void update(int index, int value) { while (index <= size) { tree[index] += value; index += index & (-index); } } // 查询某一段区间的前缀和 int query(int index) const { int sum = 0; while (index > 0) { sum += tree[index]; index -= index & (-index); } return sum; } }; int countInversions(vector<int>& nums) { if (nums.empty()) return 0; // 离散化过程 vector<int> sortedNums(nums.begin(), nums.end()); sort(sortedNums.begin(), sortedNums.end()); sortedNums.erase(unique(sortedNums.begin(), sortedNums.end()), sortedNums.end()); auto getRank = [&](const int& num) -> int { return lower_bound(sortedNums.begin(), sortedNums.end(), num) - sortedNums.begin() + 1; }; int rankSize = sortedNums.size(); FenwickTree fenwick(rankSize); long long inversionCount = 0; for (auto it = nums.rbegin(); it != nums.rend(); ++it) { // 反向迭代 int rank = getRank(*it); inversionCount += fenwick.query(rank - 1); // 统计前面比它小的数 fenwick.update(rank, 1); // 插入当前数 } return inversionCount; } int main() { vector<int> nums = {7, 5, 6, 4}; cout << "Number of inversions: " << countInversions(nums) << endl; // 输出应为 5 return 0; } ``` 上述代码定义了一个 `FenwickTree` 类用于管理树状数组的操作,并提供了一种通用的方式来计算任意整数序列中的逆序对数目[^3]。 --- #### 关键点解析 1. **离散化** 原始数组可能包含非常大的整数值,这会显著增加树状数组的空间需。因此,通常需要将原始数组映射到一个小范围内的连续整数集合上,这一过程称为离散化[^4]。 2. **反向遍历** 计算逆序对的关键是从最后一个元素开始逐步向前扫描整个数组。这样做的好处是可以动态维护已知范围内所有可能出现的小于当前元素的次数。 3. **时间复杂度分析** 整个算法由两部分组成:一是排序与去重后的离散化阶段;二是实际运用树状数组完成倒置对统计的部分。总体来看,这两个环节都维持在 \(O(n \log n)\),其中 \(n\) 表示输入列表大小。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值