当前位置 博文首页 > ttoobne:2019牛客暑期多校训练营(第七场)H Pair(数位dp)

    ttoobne:2019牛客暑期多校训练营(第七场)H Pair(数位dp)

    作者:[db:作者] 时间:2021-08-30 10:34

    题目链接

    题解:

    数位dp。有两个限制条件,需要枚举两个数字,那么 dp 需要开五个维度,分别是 位数、第一个限制条件的状态 (0 代表不满足,1 代表可能满足,2 代表满足)、第二个限制条件的状态、第一个数字的该位二进制值、第二个数字的该位二进制值。

    那么接下来就是经典的数位 dp 了,要注意减去 x 为?0 或者 y 为 0 的情况。

    代码:

    #include <bits/stdc++.h>
    using namespace std;
    
    typedef long long ll;
    typedef unsigned long long ull;
    #define int ll
    #define PI acos(-1.0)
    #define INF 0x3f3f3f3f3f3f3f3f
    #define P pair<int, int>
    #define fastio ios::sync_with_stdio(false), cin.tie(0)
    const int mod = 998244353;
    const int M = 1000000 + 10;
    const int N = 30 + 10;
    
    int t;
    int da[N], db[N], dc[N];
    int dp[N][3][3][2][2];
    // digit, state_and, state_xor, limit_x, limit_y
    // state == 0 impossible
    // state == 1 maybe
    // state == 2 certain
    
    int dfs(int pos, int stand, int stxor, int limx, int limy)
    {
        if(pos < 0) return (stand == 2) || (stxor == 2);
        if(!stand && !stxor) return 0;
        if(dp[pos][stand][stxor][limx][limy] != -1) return dp[pos][stand][stxor][limx][limy];
        int upx = limx ? da[pos] : 1, upy = limy ? db[pos] : 1, ans = 0;
        for(int i = 0; i <= upx; i ++) {
            for(int j = 0; j <= upy; j ++) {
                int xandy = (i & j), xxory = (i ^ j);
                if((!stand || ((stand == 1) && xandy < dc[pos]))
                   && (!stxor || ((stxor == 1) && xxory > dc[pos]))) continue;
                int sa = stand, sx = stxor;
                if(sa == 1) {
                    if(xandy > dc[pos]) sa = 2;
                    else if(xandy < dc[pos]) sa = 0;
                }
                if(sx == 1) {
                    if(xxory < dc[pos]) sx = 2;
                    else if(xxory > dc[pos]) sx = 0;
                }
                ans += dfs(pos - 1, sa, sx, limx && (i == upx), limy && (j == upy));
            }
        }
        dp[pos][stand][stxor][limx][limy] = ans;
        return ans;
    }
    
    void solve()
    {
        memset(dp, -1, sizeof dp);
        memset(da, 0, sizeof da);
        memset(db, 0, sizeof db);
        memset(dc, 0, sizeof dc);
        int a, b, c, lena, lenb, lenc, aa, bb, cc;
        lena = lenb = lenc = -1;
        cin >> a >> b >> c;
        aa = a, bb = b, cc = c;
        while(aa) da[++lena] = aa & 1, aa >>= 1;
        while(bb) db[++lenb] = bb & 1, bb >>= 1;
        while(cc) dc[++lenc] = cc & 1, cc >>= 1;
        int pos = max(max(lena, lenb), lenc);
        cout << dfs(pos, 1, 1, 1, 1) - min(a, c - 1) - min(b, c - 1) - 1 << endl;
    }
    
    signed main()
    {
        cin >> t;
        while(t --) solve();
        return 0;
    }
    
    /*
    
      Rejoicing in hope, patient in tribulation.
    
    */
    

    ?

    cs