Blake is a CEO of a large company called "Blake Technologies". He loves his company very much and he thinks that his company should be the best. That is why every candidate needs to pass through the interview that consists of the following problem.
We define function f(x, l, r) as a bitwise OR of integers xl, xl + 1, ..., xr, where xi is the i-th element of the array x. You are given two arrays a and b of length n. You need to determine the maximum value of sum f(a, l, r) + f(b, l, r) among all possible 1 ≤ l ≤ r ≤ n.
The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the length of the arrays.
The second line contains n integers ai (0 ≤ ai ≤ 109).
The third line contains n integers bi (0 ≤ bi ≤ 109).
Print a single integer — the maximum value of sum f(a, l, r) + f(b, l, r) among all possible 1 ≤ l ≤ r ≤ n.
5 1 2 4 3 2 2 3 3 12 1
22
10 13 2 7 11 8 4 9 8 5 1 5 7 18 9 2 3 0 11 8 6
46
Bitwise OR of two non-negative integers a and b is the number c = a OR b, such that each of its digits in binary notation is 1 if and only if at least one of a or b have 1 in the corresponding position in binary notation.
In the first sample, one of the optimal answers is l = 2 and r = 4, because f(a, 2, 4) + f(b, 2, 4) = (2 OR 4 OR 3) + (3 OR 3 OR 12) = 7 + 15 = 22. Other ways to get maximum value is to choose l = 1 and r = 4, l = 1 and r = 5, l = 2 and r = 4, l = 2 and r = 5, l = 3 and r = 4, or l = 3 and r = 5.
In the second sample, the maximum value is obtained for l = 1 and r = 9.
题意就是给两个数组之后求出一段使得f(a, l, r) + f(b, l, r)最大
其中定义f(a,b,c)为数组a从b到c取逻辑或运算的值;
对于a数组设sum[i]为1~i的最大值,则sum[i]=max(sum[i]|sum[i-1],sum[i]);
b数组同理;
之后将a,b数组所对应的sum[i](其中i~n)相加取最大值就是答案了.
#include<stdio.h>
#include<algorithm>
using namespace std;
int main()
{
int a[1005];
int b[1005];
int c[1005];
int d[1005];
int sum[1005];
int n;
scanf("%d",&n);
for (int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for (int i=0;i<n;i++)
{
scanf("%d",&b[i]);
}
c[0]=a[0];
d[0]=b[0];
int maxx=-1;
for (int i=1;i<n;i++)
{
c[i]=max(a[i],c[i-1]|a[i]);
d[i]=max(b[i],d[i-1]|b[i]);
}
for (int i=0;i<n;i++)
{
sum[i]=c[i]+d[i];
if (maxx<sum[i]) maxx=sum[i];
}
printf("%d\n",maxx);
}