codeforces 165E Compatible Numbers(位运算)【模板】

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.

Example
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与其他元素的亦或值都等于0,则输出-1,否则输出与其他任意元素的亦或值的值), 我们可以每次把所有元素的亦或值存起来,处理完再输出。

 详解看代码注释

 【AC代码】

 

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=1e6+5;
const int inf=(1<<22)-1;
int m,n;
int a[10000005],b[inf];

int main()
{
        scanf("%d",&m);
        for(int i=1;i<=m;++i)
        {
            scanf("%d",&a[i]);
            b[inf^a[i]]=a[i];//保存所有亦或值
        }
        for(int i=inf;i>=0;--i)//遍历一遍  
        {
            if(!b[i])//没有相应的亦或值
            {
                for(int j=0;j<22;++j)
                    if(b[i|(1<<j)])//如果第j位变为1
                     b[i]=b[i|(1<<j)];//把第j位变为1
            }
        }
        for(int i=1;i<=m;++i)
        {
            if(i-1!=0) printf(" ");
            if(b[a[i]]) printf("%d",b[a[i]]);//如果a[i]亦或值 不为0  则说明不相溶
            else printf("-1");
        }
        printf("\n");
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值