japan(树状数组求逆序数)

本文介绍了一个算法问题,涉及计算日本岛屿上建设的高速公路之间的交叉点数量。通过将城市配对视为坐标点,并利用树状数组求解逆序数的方法,实现了高效计算。

http://poj.org/problem?id=3067

Description

Japan plans to welcome the ACM ICPC World Finals and a lot of roads must be built for the venue. Japan is tall island with N cities on the East coast and M cities on the West coast (M <= 1000, N <= 1000). K superhighways will be build. Cities on each coast are numbered 1, 2, ... from North to South. Each superhighway is straight line and connects city on the East coast with city of the West coast. The funding for the construction is guaranteed by ACM. A major portion of the sum is determined by the number of crossings between superhighways. At most two superhighways cross at one location. Write a program that calculates the number of the crossings between superhighways.

Input

The input file starts with T - the number of test cases. Each test case starts with three numbers – N, M, K. Each of the next K lines contains two numbers – the numbers of cities connected by the superhighway. The first one is the number of the city on the East coast and second one is the number of the city of the West coast.

Output

For each test case write one line on the standard output:
Test case (case number): (number of crossings)

Sample Input

1
3 4 4
1 4
2 3
3 2
3 1

Sample Output

Test case 1: 5

Source

Southeastern Europe 2006

题意:日本岛东海岸与西海岸分别有N和M个城市,现在修高速公路连接东西海岸的城市,求交点个数。记每条告诉公路为(x,y), 即东岸的第x个城市与西岸的第y个城市修一条路。当两条路有交点时,满足(x1-x2)*(y1-y2) < 0。所以,将每条路按x从小到达排序,若x相同,按y从小到大排序。 然后按排序后的公路用树状数组在线更新,求y的逆序数之 和 即为交点个数。

上面说的可能有点难理解,详细说明如下。

记第i条边的端点分别为xi,yi。

方法:

1.就是将x坐标,由小到大排序后,求y坐标的逆序数。但是要注意,排序方法是在当x相同的情况下,y要按照有小到大排序,这样才可以。(可以画一下)

2.maxn之前设成了1000,但是要知道,最多有1000*1000个连线。否则RE

3.逆序数这样想。比如2 2 3 4 1.想到,当我们从头开始,遇到第一个2,此时要看后边比2小的有几个。但是树状数组我们没法知道未来的,只能算已经扫进去的,所以倒过来,就看自己能否跟前边的来一个贡献。就看到了当前,比他大的数有几个。

代码:

#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<memory.h>
using namespace std;
typedef long long LL;
const int maxn=1023004;
LL c[maxn];
struct node{
    int x,y;
}a[maxn];
int cmp(node a,node b){
    if(a.x==b.x)
        return a.y<b.y;
    return a.x<b.x;
}
int lowbit(int x){
    return x&(-x);
}
void add(int x){
    int i=x;
    for(;i<=maxn;i+=lowbit(i)){
        c[i]+=1;
    }
}
long long sum(int x){
    int i=x;long long sum=0;
    for(;i>0;i-=lowbit(i)){
        sum+=c[i];
    }
    return sum;
}
int main()
{
    int t,n,m,k;
    int cas=0;
    scanf("%d",&t);
    while(t--){
        memset(c,0,sizeof(c));
        memset(a,0,sizeof(a));
        cas++;
        scanf("%d%d%d",&n,&m,&k);
        for(int i=1;i<=k;i++){
            scanf("%d%d",&a[i].x,&a[i].y);
        }
        sort(a+1,a+1+k,cmp);
        /*for(int i=1;i<=k;i++){
            cout<<a[i].x<<" "<<a[i].y<<endl;
        }
        */
        long long ans=0;
        for(int i=1;i<=k;i++){
            ans+=( sum(maxn) - sum(a[i].y) );
            add(a[i].y);
        }
        printf("Test case %d: %lld\n",cas,ans);
    }
}
/*
30
3 3 3
1 3
2 2
3 1

3 4 4
1 4
2 3
3 2
3 1

2 3 2
1 2
2 1

4 4 5
1 2
3 2
3 3
3 4
4 1


*/

 

### 使用树状数组(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、付费专栏及课程。

余额充值