Daniel and Spring Cleaning【数位DP】【Codeforces 1245 F】

Codeforces Round #597 (Div. 2) F


  这道题化简一下就是让我们求有上下限的2进制数中有几对满足每一位的相"&"值不为1的对数。

  那么,首先看到这个1e9就会让人想到数位DP,然后接着就是如何去求的这样一个问题。

  我们不如将上下限看作一个二维空间,那么就是这样的一张图:

  我们现在想知道的是图中的矩形块的面积,也就是最后的答案。

  那么,不就是area(R, R) - area(L-1, R) - area(R, L-1) + area(L-1, L-1)

  然后就是这里的数位dp的记忆化操作了(如果不记忆化,复杂度是O(N)),然后记忆化之后的复杂度是O(log(N))。我们的记忆化dp是dp[ ][ ][ ],dp [下一位是第几位] [第一维是否是limit] [第二维是否是limit] 

#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define INF 0x3f3f3f3f
#define eps 1e-9
#define HalF (l + r)>>1
#define lsn rt<<1
#define rsn rt<<1|1
#define Lson lsn, l, mid
#define Rson rsn, mid+1, r
#define QL Lson, ql, qr
#define QR Rson, ql, qr
#define myself rt, l, r
using namespace std;
typedef unsigned long long ull;
typedef unsigned int uit;
typedef long long ll;
ll dp[34][2][2];
int L, R, x[34], y[34];
inline ll dfs(int pos, bool limit_L, bool limit_R)
{
    if(!pos) return 1;
    if(dp[pos][limit_L][limit_R] ^ -1) return dp[pos][limit_L][limit_R];
    ll res = 0;
    int up_L = limit_L ? x[pos] : 1, up_R = limit_R ? y[pos] : 1;
    for(int i=0; i<=up_L; i++)
    {
        for(int j=0; j<=up_R; j++)
        {
            if(i & j) continue;
            res += dfs(pos - 1, limit_L && (up_L == i), limit_R && (up_R == j));
        }
    }
    dp[pos][limit_L][limit_R] = res;
    return res;
}
inline ll solve(int l, int r)
{
    if(l < 0 || r < 0) return 0;
    memset(dp, -1, sizeof(dp));
    int tot = 0;
    for(; l || r; l >>= 1, r >>= 1) { x[++tot] = l & 1; y[tot] = r & 1; }
    return dfs(tot, true, true);
}
int main()
{
    int T; scanf("%d", &T);
    while(T--)
    {
        scanf("%d%d", &L, &R);
        printf("%lld\n", solve(R, R) - solve(R, L - 1) - solve(L - 1, R) + solve(L - 1, L - 1));
    }
    return 0;
}

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wuliwuliii

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值