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

链接:H-Pair
在这里插入图片描述
题意:
求 A & B < C 或者 A ^ B > C 的 (A, B)的对数。
思路:
还是数位 dp ,把数拆成二进制一位一位考虑, 先那 & 来考虑 还是记录 当前的值是不是和 C 完全相同,如果相同就是 1 ,如果前面位已经出现过小于 C的了 就是 0,如果前面出现过 大于 C 的 了 就是 2 代表不合法。如果当前两个状态都不合法,则无法进入下一个 dfs。最后判断一下 两个状态是不是有一个是 0 就好了 是就返回 1 ,还有 A,B 都大于 1 所以考虑一下前导 0 ,如果前面全是 0 也是不行的。
代码:

#include <iostream>
#include <cstdio>
#include <map>
#include <math.h>
#include <queue>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 1e2 + 7;
const int mod=1e9 + 7;
ll dp[maxn][3][3][4][4][2][2];
int a[maxn],b[maxn],A,B,C,T,c[maxn],cnt;
char s[maxn];
ll dfs(int pos, int limit1, int limit2,int st1 ,int st2 ,int lead1 ,int lead2){
    
    
    if(pos == -1){
    
    
       return (st1==0||st2==0)&&lead1==0&&lead2==0;
    }
    if(dp[pos][limit1][limit2][st1][st2][lead1][lead2]!=-1) {
    
    
        return dp[pos][limit1][limit2][st1][st2][lead1][lead2];
    }
    int up1 = limit1 ? a[pos] : 1 ;
    int up2 = limit2 ? b[pos] : 1 ;
    ll temp = 0;
    for(int i = 0; i <= up1; i++){
    
    
        for(int j = 0; j <= up2; j++){
    
    
            int s1,s2;
            if(st1==2&&st2==2) continue;
               s1 = st1,s2 = st2;
               if(s1 == 1 && (i & j) < c[pos]) s1 = 2;
               if(s1 == 1 && (i & j) > c[pos]) s1 = 0;
               if(s2 == 1 && (i ^ j) > c[pos]) s2 = 2;
               if(s2 == 1 && (i ^ j) < c[pos]) s2 = 0;
 
               temp += dfs(pos - 1, limit1&&i==a[pos],limit2&&j==b[pos],s1,s2,lead1&&i==0,lead2&&j==0);

     
        }
    }
    dp[pos][limit1][limit2][st1][st2][lead1][lead2]= temp ;
    return temp;
}
ll solve (int A,int B){
    
    
   cnt=0;
   for(int i = 0; i <= 31; i ++){
    
    
        a[i] = (A >> i) & 1;
        b[i] = (B >> i) & 1;
        c[i] = (C >> i) & 1;
    }
    return  dfs(31,1,1,1,1,1,1);
}
int main(){
    
    
    scanf("%d",&T);
    while(T--){
    
    
        memset(dp,-1,sizeof(dp));
        scanf("%d%d%d",&A,&B,&C);
        cout<<solve(A,B)<<endl;
    }
}

猜你喜欢

转载自blog.csdn.net/hddddh/article/details/107649591
今日推荐