之前我们已经通过一道例题初步感受离散化的思想,现在进行比较系统的归纳整理。

离散化应用与进阶

1. 离散化基础概念

离散化(Discretization)是将连续数据转换为离散值的过程,在编程中常用于处理大数据范围或浮点数问题。

基本思想

  • 将大范围的数值映射到小范围的连续整数
  • 保持原始数据的相对大小关系
  • 适用于值域大但数据稀疏的场景

基本步骤

  1. 排序:将所有待离散化的值排序
  2. 去重:去除重复的值
  3. 映射:建立值到索引的映射关系

2. 离散化实现

基本实现代码(C++)

vector<int> discrete(vector<int>& nums) {
    vector<int> sorted(nums);
    sort(sorted.begin(), sorted.end());
    sorted.erase(unique(sorted.begin(), sorted.end()), sorted.end());
    
    vector<int> result(nums.size());
    for (int i = 0; i < nums.size(); i++) {
        result[i] = lower_bound(sorted.begin(), sorted.end(), nums[i]) - sorted.begin();
    }
    return result;
}

离散化公式表示

给定原始数据集合 X={x1,x2,...,xn}X = \{x_1, x_2, ..., x_n\},离散化后的集合 Y={y1,y2,...,yn}Y = \{y_1, y_2, ..., y_n\} 满足:

yi=rank(xi)y_i = rank(x_i)

其中 rank(xi)rank(x_i) 表示 xix_i 在排序去重后的数组中的位置(从0或1开始)。

3. 离散化进阶应用

3.1 二维离散化

处理二维平面上的点集,常用于计算几何问题。

void twoD_discrete(vector<pair<int, int>>& points) {
    vector<int> xs, ys;
    for (auto& p : points) {
        xs.push_back(p.first);
        ys.push_back(p.second);
    }
    
    sort(xs.begin(), xs.end());
    xs.erase(unique(xs.begin(), xs.end()), xs.end());
    
    sort(ys.begin(), ys.end());
    ys.erase(unique(ys.begin(), ys.end()), ys.end());
    
    for (auto& p : points) {
        p.first = lower_bound(xs.begin(), xs.end(), p.first) - xs.begin();
        p.second = lower_bound(ys.begin(), ys.end(), p.second) - ys.begin();
    }
}

3.2 带权离散化

考虑每个值的权重进行离散化,常用于统计问题。

Yi=∑j=1rank(Xi)wjY_i = \sum_{j=1}^{rank(X_i)} w_j

其中 wjw_j 是第j个离散值的权重。

3.3 动态离散化

处理动态增加的数据流,使用平衡二叉搜索树维护离散化映射。

#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;

tree<int, null_type, less<int>, rb_tree_tag, 
     tree_order_statistics_node_update> tr;

void dynamic_discrete(int x) {
    if (!tr.find(x)) tr.insert(x);
    int rank = tr.order_of_key(x); // 获取x的排名
}

4. 离散化与数据结构结合

4.1 离散化+线段树

处理大值域区间查询问题。

// 离散化后建立线段树
vector<int> alls; // 所有待离散化的值
sort(alls.begin(), alls.end());
alls.erase(unique(alls.begin(), alls.end()), alls.end());

// 线段树大小为alls.size()

4.2 离散化+树状数组

用于高效处理前缀和问题。

// 离散化后使用树状数组
vector<int> c(alls.size() + 1); // 树状数组从1开始

void add(int x, int k) {
    x = lower_bound(alls.begin(), alls.end(), x) - alls.begin() + 1;
    for (; x <= alls.size(); x += x & -x) c[x] += k;
}

5. 离散化优化技巧

5.1 离线处理

对于多次查询问题,可以先收集所有可能的值进行统一离散化。

5.2 离散化与哈希结合

当需要频繁查询离散化结果时,可以使用哈希表存储映射关系。

unordered_map<int, int> mapping;
for (int i = 0; i < sorted.size(); i++) {
    mapping[sorted[i]] = i;
}

5.3 离散化与双指针

结合双指针算法处理离散化后的数据,可以优化某些区间问题的时间复杂度。

6. 离散化数学表示进阶

对于更复杂的离散化场景,可以使用数学函数表示:

给定原始值 xx,离散化后的值 yy 可以表示为:

y=f(x)=∑i=1n[xi≤x]y = f(x) = \sum_{i=1}^n [x_i \leq x]

其中 [xi≤x][x_i \leq x] 是指示函数,当 xi≤xx_i \leq x 时为1,否则为0。

对于加权离散化:

y=f(x)=∑i=1nwi⋅[xi≤x]y = f(x) = \sum_{i=1}^n w_i \cdot [x_i \leq x]

7. 离散化的局限性

  1. 无法处理插入新值:一旦离散化完成,新增值需要重新离散化
  2. 精度损失:原始数据的精确值信息丢失
  3. 不适用于需要精确值的场景:如某些几何计算

离散化是算法竞赛和数据处理中的重要技巧,合理使用可以大幅提升程序效率,特别是在处理大值域问题时。