J - Compatible Numbers(压状dp)

题目

Two integers x and y are compatible, if the result of their bitwise “AND” equals zero, that is, a & b = 0. For example, numbers 90 (10110102) and 36 (1001002) are compatible, as 10110102 & 1001002 = 02, and numbers 3 (112) and 6 (1102) are not compatible, as 112 & 1102 = 102.

You are given an array of integers a1, a2, …, an. Your task is to find the following for each array element: is this element compatible with some other element from the given array? If the answer to this question is positive, then you also should find any suitable element.
Input

The first line contains an integer n (1 ≤ n ≤ 106) — the number of elements in the given array. The second line contains n space-separated integers a1, a2, …, an (1 ≤ ai ≤ 4·106) — the elements of the given array. The numbers in the array can coincide.
Output

Print n integers ansi. If ai isn’t compatible with any other element of the given array a1, a2, …, an, then ansi should be equal to -1. Otherwise ansi is any such number, that ai & ansi = 0, and also ansi occurs in the array a1, a2, …, an.
Examples
Input

2
90 36

Output

36 90

Input
4
3 6 3 6

Output
-1 -1 -1 -1
Input

5
10 6 9 8 2
Output

-1 8 2 2 8

转移方程 dp[i^(1<<j)] = dp[i];

先通过a[i]来获得一部分数据, dp [ k ^ a[i] ] = a[i];例如dp[11111 ^ 101] =dp[11010] = 101,但这样做完只获得了一小部分可以知道的数据。由于 11010去掉任意其中的1,比如变成10010,11000与101进行&运算结果都还是0。所以dp[11010] =dp[10010] =dp[11000] = 101,推得 dp[i^(1<<j)] = dp[i];10000要由11000或者10010之类的来获得所以i要从最大值开始自减。最后推得可以获得的全部数据,dp[a[i]]是0,则说明就没有 k ^ a[j] 和它的去任意1的值,出现等于a[i]的,就不存在。dp[a[i]] != 0,说明是由已有数据得到或推出得到的,对应的dp值必然是a[ ]中的元素。
你也可以写出这样 dp[i]=dp[i|(1<<j)]; 这时候得dp[i] == 0,dp[i|(1<<j)]给i各个位置加1如果dp值存在更新没问题,是0对结果也没影响。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
int  dp[(1<<22)-1];

int a[1000010];
int main(){
    int n, i, k = (1<<22)-1, j;
    while(~scanf("%d", &n)){
    memset(a, 0, sizeof(a));
    memset(dp, 0, sizeof(dp));
    for(i = 0; i < n; i++){
        scanf("%d", &a[i]);
        dp[k^a[i]] = a[i];
    }
    for(i = k; i >= 0; i--){
        if(dp[i]){
            for(j = 0; j < 22; j++)
                if(!dp[i^(1<<j)]&&(i&(1<<j)))
                    dp[i^(1<<j)] = dp[i];
        }
    }
    int flag = 0;
    for(i = 0; i < n; i++){
        if(flag++ != 0)
            printf(" ");

        if(dp[a[i]])
            printf("%d", dp[a[i]]);
        else
            printf("-1");
    }
        printf("\n");
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值