【杂文】离散化的两种不同姿势

新博客:debug18.com 使用hexo搭建,欢迎来踩~

今天才见识到两种不同的离散化姿势,果然我还是太弱了么……


第一种:原数组 sort、unique 之后,对每个数 lower_bound 查询在排序后数组中的位置,此即为新值。

代码:

1     vector<int> arr, tmp;
2     // do something
3     tmp = arr;
4     sort(tmp.begin(), tmp.end());
5     tmp.resize(unique(tmp.begin(), tmp.end()) - tmp.begin());
6     for (int i = 0; i < arr.size(); i++)
7         arr[i] = lower_bound(tmp.begin(), tmp.end(), arr[i]) - tmp.begin();

第二种:原数组 sort 之后,用类似计算后缀树组的方式计算出 rank 数组(rank[i] 表示原数组第 i 个数在排好序中的数组中的排名)(计算 rank 时可以用一些技巧省去之前的 unique)

代码:(代码中省略了 rank 数组)

1     vector<int> arr;
2     // do something
3     vector<pair<int, int> > tmp;
4     for (int i = 0; i < arr.size(); i++)
5         tmp[i] = make_pair(arr[i], i);
6     sort(tmp.begin(), tmp.end());
7     arr[tmp[0].second] = 1;
8     for (int i = 1; i < arr.size(); i++)
9         arr[tmp[i].second] = arr[tmp[i-1].second] + (tmp[i].first != tmp[i-1].first);

 赶脚第二种更好的样子……

posted on 2015-08-09 22:02  __debug  阅读(345)  评论(1编辑  收藏  举报

导航