E. Compatible Numbers

http://codeforces.com/problemset/problem/165/E

E. Compatible Numbers

time limit per test

4 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

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

Copy

2
90 36

Output

Copy

36 90

Input

Copy

4
3 6 3 6

Output

Copy

-1 -1 -1 -1

Input

Copy

5
10 6 9 8 2

Output

Copy

-1 8 2 2 8

嗯~

题意 

两个整数 x 和 y 是 兼容的,如果它们的位运算 "AND" 结果等于 0,亦即 a & b = 0 。例如,数 90 (10110102) 和 36 (1001002) 是兼容的,因为 10110102 & 1001002 = 02;而数 3 (112)和 6 (1102) 是不兼容的,因为 112 & 1102 = 102 。

给定一个整数数组 a1, a2, ..., an 。您的任务是判断每个数组元素:这个元素是否与给定数组中的某个其它元素兼容?如果问题的答案是肯定的,则应找出任意一个匹配的元素。

我们发现给的数据范围是400w,是可以直接用数组开下的,考虑到&运算的时候只有原数字位位1和另一个数字相同位为1的时候才会导致不匹配。

所以我们利用贪心的思想,先把能与这个数匹配的最大数直接存入数组,之后从后往前遍历,如果遇到没有匹配的数字,就考虑比他多一位1的数字有没有匹配,因为在相同位上1总为0的子集,因此这样预处理之后可直接输出。

代码:

#include<bits/stdc++.h>
using namespace std;
const double eps = 1e-9;
const int maxn = 1e6 + 10;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
int N,M,tmp,K;
int dp[1 << 23];
int a[maxn];
int main()
{
    scanf("%d",&N);
    for(int i=1;i<=N;i++){
        int x; scanf("%d",&x); a[i] = x;
        dp[x ^ ((1 << 23) - 1)] = x;
    }
    for(int i = (1 << 23) - 1; i >= 0 ; i --){
        if(!dp[i]){
            for(int j = 0; j < 23; j ++){
                if(dp[i | (1 << j)]){
                    dp[i] = dp[i | (1 << j)];
                    break;
                }
            }
        }
    }
    for(int i=1;i<=N;i++){
        if(dp[a[i]]) printf("%d ",dp[a[i]]);
        else printf("-1 ");
    }
    return 0;
}
/*
8388608
*/
发布了565 篇原创文章 · 获赞 110 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/xianpingping/article/details/90705579