light oj 1032 - Fast Bit Calculations(数位dp 记忆化搜索解法)

题目链接:点击打开链接

//二进制表示的数 的数位dp

#include<stdio.h>
#include<string.h>

#define ll long long

ll dp[40][40][2];//dp[pos][s][pre]存 位置在pos 前面出现过s个1 1相邻的情况 二进制的前一位是pre 的状态的答案
int digit[40];

ll dfs(int pos,int s,int pre,int doing)//位置在pos 前面出现过s个1 1相邻的情况 二进制的前一位是pre doing 标记是否为上界
{
    if(pos==-1)return s;
    if(!doing && dp[pos][s][pre]!=-1)return dp[pos][s][pre];//记忆化

    int End,i;
    ll ans=0;

    End=doing ? digit[pos]:1;

    for(i=0;i<=End;i++)
    {
        if(pre==1&&i==1)//前面一位是1 当前一位也是1 s+1
            ans+=dfs(pos-1,s+1,1,doing && i==End);
        else if(i==1)//前面一位不是1 当前一位是1 s不加 pre标记为1
            ans+=dfs(pos-1,s,1,doing && i==End);
        else// 其他情况 pre为0(因为二进制只有0 1)
            ans+=dfs(pos-1,s,0,doing && i==End);
    }

    if(!doing)
        dp[pos][s][pre]=ans;
    return ans;

}
ll solve(ll x)
{
    int l=0;
    memset(dp,-1,sizeof(dp));
    memset(digit,0,sizeof(digit));

    while(x>0)
    {
        digit[l++]=x%2;//将当前数字按二进制存起来
        x=x/2;
    }
    dfs(l-1,0,0,1);

}
int main()
{
    int t,v=1;
    ll n;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%lld",&n);
        printf("Case %d: %lld\n",v++,solve(n));
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这是一道经典的位运算题目,考察对二进制的理解和位运算的熟练程度。 题目描述: 给定一个长度为 $n$ 的数组 $a$,初始时每个数的值都为 $0$。现在有 $m$ 个操作,每个操作为一次询问或修改。 对于询问,给出两个整数 $l,r$,求 $a_l \oplus a_{l+1} \oplus \cdots \oplus a_r$ 的值。 对于修改,给出一个整数 $x$,表示将 $a_x$ 的值加 $1$。 输入格式: 第一行两个整数 $n,m$。 接下来 $m$ 行,每行描述一次操作,格式如下: 1 l r:表示询问区间 $[l,r]$ 的异或和。 2 x:表示将 $a_x$ 的值加 $1$。 输出格式: 对于每个询问操作,输出一个整数表示答案,每个答案占一行。 数据范围: $1 \leq n,m \leq 10^5$,$0 \leq a_i \leq 2^{30}$,$1 \leq l \leq r \leq n$,$1 \leq x \leq n$ 输入样例: 5 5 2 1 2 3 1 2 4 2 2 1 1 5 输出样例: 0 2 解题思路: 对于询问操作,可以利用异或的性质,即 $a \oplus b \oplus a = b$,将 $a_l \oplus a_{l+1} \oplus \cdots \oplus a_r$ 转化为 $(a_1 \oplus \cdots \oplus a_{l-1}) \oplus (a_1 \oplus \cdots \oplus a_r)$,因为两个前缀异或后的结果可以相互抵消,最后的结果即为 $a_1 \oplus \cdots \oplus a_{l-1} \oplus a_1 \oplus \cdots \oplus a_r = a_l \oplus \cdots \oplus a_r$。 对于修改操作,可以将 $a_x$ 对应的二进制数的每一位都分离出来,然后对应位置进行修改即可。由于只有加 $1$ 操作,所以只需将最后一位加 $1$ 即可,其余位不变。 参考代码:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值