Codeforces 165E Compatible Numbers

来源:互联网 发布:2016年网络大电影 编辑:程序博客网 时间:2024/06/05 06:17

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.

Sample test(s)
input
290 36
output
36 90
input
43 6 3 6
output
-1 -1 -1 -1
input
510 6 9 8 2
output
-1 8 2 2 8

我们知道:0&1=0,1&1=1,0&0=0;

那么对于每个输入的数我们存下和最大数据(1<<22)-1的抑或值。

例如:输入数据为0101的话,假设最大值有4位1,则:0101^1111=1010,那么1010是符合条件的

值因为1010&0101=0但是我们注意到对于抑或值为1的位证明原数位上值为0,但是相与

的时候是0或1都可以。所以我们要扩展状态找到每种情况的值。

#include<cstdio>#include<cstring>#include<algorithm>#include<vector>#include<string>#include<iostream>#include<queue>#include<cmath>#include<map>#include<stack>#include<bitset>using namespace std;#define REPF( i , a , b ) for ( int i = a ; i <= b ; ++ i )#define REP( i , n ) for ( int i = 0 ; i < n ; ++ i )#define CLEAR( a , x ) memset ( a , x , sizeof a )typedef long long LL;typedef pair<int,int>pil;const int INF = 0x3f3f3f3f;//0&0=0 1&0=0,1&1=1;//O(4*1e6*20)const int maxn=1e7;int a[maxn];int ans[maxn];int n;int main(){    while(~scanf("%d",&n))    {        CLEAR(ans,-1);        int st=(1<<22)-1;        REPF(i,1,n)        {            scanf("%d",&a[i]);            ans[st^a[i]]=a[i];        }        for(int i=st;i>=0;i--)        {            if(ans[i]==-1)            {                for(int j=0;j<22;j++)                {                    if(!(i&(1<<j))&&ans[i^(1<<j)]!=-1)                    {                        ans[i]=ans[i^(1<<j)];                        break;                    }                }            }        }        REPF(i,1,n)          printf("%d ",ans[a[i]]);        puts("");    }    return 0;}/**/


0 0
原创粉丝点击