Codeforces Round #664 (Div. 2) C. Boboniu and Bit Operations (Thinking+dp)

Click here for the topic link! !
The main idea of ​​the topic: For each number in a, select a number in b to perform & operation to get c, and finally calculate all c| to be as small as possible.
Idea: The
first time I see this, I can think of dp, because the number selected each time may be small even if it is large at the end or after calculation, so greedy is definitely not good.
Then we start to consider the status, what factors affect our decision-making, which is the combination of the previous ai and which bj, then can we determine which combination he wants to combine with? No, because of the OR operation, we cannot guarantee no aftereffect. Then we have to consider saving all possible states, and consider designing a state that can judge whether a certain number exists. Obviously, the maximum of a and b is 2^9, and the maximum is 511. That is, the final result will not exceed this number. So we consider setting dp[i][j] to indicate whether j can appear after ci and the previous c or operation. The value is 1, otherwise it is 0. Finally, traverse the dp array of the nth row, and the first number that appears is the smallest answer.

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int inf=0x3f3f3f3f;
const int N=1e5+10;
int a[250],b[250],dp[250][1024],n,m,ans[250][250];
int main()
{
    
    
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++) scanf("%d",&a[i]);
    for(int i=1;i<=m;i++) scanf("%d",&b[i]);
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
        ans[i][j]=(a[i]&b[j]);
    for(int i=1;i<=m;i++) dp[1][ans[1][i]]=1;
    for(int i=2;i<=n;i++)
    for(int j=1;j<=m;j++)
    for(int k=0;k<=(1<<9)-1;k++){
    
    
        if(dp[i-1][k]) dp[i][k|ans[i][j]]=1;
    }
    int res;
    for(int i=0;i<=(1<<9)-1;i++){
    
    
        if(dp[n][i]) {
    
    
            res=i;
            break;
        }
    }
    printf("%d\n",res);
    return 0;
}

Guess you like

Origin blog.csdn.net/amazingee/article/details/107977370