天天看點

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

Codeforces Round #597 (Div. 2) F

  這道題化簡一下就是讓我們求有上下限的2進制數中有幾對滿足每一位的相"&"值不為1的對數。

  那麼,首先看到這個1e9就會讓人想到數位DP,然後接着就是如何去求的這樣一個問題。

  我們不如将上下限看作一個二維空間,那麼就是這樣的一張圖:

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

  我們現在想知道的是圖中的矩形塊的面積,也就是最後的答案。

  那麼,不就是

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

  然後就是這裡的數位dp的記憶化操作了(如果不記憶化,複雜度是O(N)),然後記憶化之後的複雜度是

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

。我們的記憶化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;
}