zoukankan      html  css  js  c++  java
  • 离散化处理

    离散化是程序设计中一个非常实用的技巧,可以有效的降低时间复杂度。基本思想就是在
    众多可能的情况中“只考虑我需要用的值“。
    这篇文章中主要是讨论了很多计算几何部分的离散化处理。

    离散化处理的方式很多,比如使用STL算法进行离散化:
    思路:先排序,然后删除重复元素。最后就是查找。
    每一步都用到了一个STL算法。排序sort() 删除重复unique() 查找lower_bound()
    unique():去除[l, r)中连续的重复元素。函数的返回值是修改后序列的最后一个元素。
    lower_bound():函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置,且last的位置是越界的。
    用一个例子说明:比如序列1 7 9 11 18 23 32 45 67 89。
    int pos=lower_bound(a,a+10,32)-a;   pos =6
    int pos=lower_bound(a,a+10,9)-a;      pos =2
    int pos=lower_bound(a,a+10,89)-a;    pos =9
    int pos=lower_bound(a,a+10,33)-a;   pos =7
    int pos=lower_bound(a,a+10,65)-a;   pos =8

    这里插入的位置开始下标是从0开始的,若要从1开始则可以使用upper_bound。 或者int pos=lower_bound(a,a+10,key)-a+1;

    所以使用STL离散化的思路就是:排序->去重->查找
    sort(sub_a,sub_a+n);
    int size=unique(sub_a,sub_a+n)-sub_a;//size为离散化后元素个数
    for(i=0;i<n;i++)    a[i]=lower_bound(sub_a,sub_a+size,a[i])-sub_a + 1;//k为b[i]经离散化后对应的值


     




  • 相关阅读:
    python-study-08
    第一周代码整理
    python-study-阶段总结
    python-study-07
    二分查找数组中与目标数字(可以是浮点型)最近的数的位置
    寻找最大数
    零件分组(stick)
    走迷宫
    自然数的拆分问题 字典序
    素数环(回溯)
  • 原文地址:https://www.cnblogs.com/gt123/p/3685656.html
Copyright © 2011-2022 走看看