http://codeforces.com/problemset/problem/578/B
B. “Or” Game
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given n numbers a1, a2, …, an. You can perform at most k operations. For each operation you can multiply one of the numbers by x. We want to make as large as possible, where denotes the bitwise OR.
Find the maximum possible value of after performing at most k operations optimally.
Input
The first line contains three integers n, k and x (1 ≤ n ≤ 200 000, 1 ≤ k ≤ 10, 2 ≤ x ≤ 8).
The second line contains n integers a1, a2, …, an (0 ≤ ai ≤ 109).
Output
Output the maximum value of a bitwise OR of sequence elements after performing operations.
Examples
inputCopy
3 1 2
1 1 1
outputCopy
3
inputCopy
4 2 3
1 2 4 8
outputCopy
79
Note
For the first sample, any possible choice of doing one operation will result the same three numbers 1, 1, 2 so the result is .
For the second sample if we multiply 8 by 3 two times we’ll get 72. In this case the numbers will become 1, 2, 4, 72 so the OR value will be 79 and is the largest possible result.
题意:n个数,k次操作,每一次能挑一个数乘以k
求最终所有数的 | (或),尽量最大
思路:
因为要尽量的大,而‘|’操作就要尽量这个数的位数越多
所以把所有的操作乘到一个数上就能找到最大值
但是每次一次次操作复杂度太高了,‘|’运算也是可以运用结合律的
用前缀和后缀来处理就快一点
代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include<algorithm>
using namespace std;
long long n,k,x,a[200005],q[200005],h[200005],ans;
long long pow(long long a,long long b){
long long ck = 1;
for(int i = 1;i <= b;i++)ck*=a;
return ck;
}
int main() {
cin >> n >> k >> x;
x=pow(x,k);
for(int i = 1;i <= n;i++) scanf("%lld",&a[i]),q[i]=q[i-1]|a[i];
for(int i = n;i > 0;i--) h[i]=h[i+1]|a[i];
for(int i = 1;i <= n;i++) {
ans = max(ans,q[i-1]|(a[i] * x)|h[i+1]);
}
cout << ans << endl;
}