2021-06-27 位运算以及离散化

位运算以及离散化

  1. 位运算
    主要说一下lowbit这个函数,返回值为数字二进制中最后一个1
    例如:10的二进制为1010,lowbit(10) = 10;改函数的具体实现
    为x & -x,原因是用二进制去与它的补码(反码+1)例如数字x的二
    进制码为10001000,那么它的反码就为01110111,它的反码就是
    01111000,那么我们就是让 10001000 & 01111000 ,得到的结果
    就是1000。
    我们可以用这个函数去计算出一个二进制数中的1的个数
#include <iostream>

using namespace std;

int n;

int lowbit(int x)
{
    return x & -x;
}

int main()
{
    int res = 0;
    int x;
    cin >> x;
    while (x) x -= lowbit(x),res ++;
    cout << res << " ";
    
    return 0;
}
  1. 离散化
    离散化的应用主要用于大规模数字但是分布很分散的题目。离散化的主要思想就是将分散的数字按照从前往后的顺序映射到我们的离散化的数组中,例如a数组中只有3个元素a[3] = 111,a[500] = 223142,a[50000] = 121.我们就需要通过离散化把这三个元素映射到b数组中的b[1],b[2],b[3]上的位置,以便于我们接下来的数据处理。
    我们通过这道例题可以对离散化的思想有个大致的理解区间和
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

typedef pair<int,int> PII;
const int N = 3e5 + 10;

int a[N],s[N];
vector<int> alls;
vector<PII> adds, query;
int n, m;

int find(int x){
    int l = 1,r = alls.size();
    while (l < r){
        int mid = l + r >> 1;
        if (x <= alls[mid]) r = mid;
        else l = mid + 1;
    }
    return r + 1;
}

int main()
{
    cin >> n >> m;
    for (int i = 1;i <= n;i ++){
        int x, c;
        cin >> x >> c;
        adds.push_back({x,c});
        alls.push_back(x);
    }
    
    for (int i = 1;i <= m;i ++){
        int l,r;
        cin >> l >> r;
        query.push_back({l,r});
        alls.push_back(l);
        alls.push_back(r);
    }
    
    sort(alls.begin(),alls.end());
    alls.erase(unique(alls.begin(),alls.end()),alls.end());
    
    for (auto item : adds){
        int x = find(item.first);
        a[x] += item.second;
    }
    
    for (int i = 1;i <= alls.size();i ++) s[i] = s[i - 1] + a[i];
    
    for (auto item : query){
        int l = find(item.first);
        int r = find(item.second);
        printf("%d\n",s[r] - s[l - 1]);
    }
    
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值