题目 | XOR to All
AtCoder Regular Contest 135
C - XOR to All
https://atcoder.jp/contests/arc135/tasks/arc135_c
Time Limit: 2 sec / Memory Limit: 1024 MB
Score :
Problem Statement
You are given a sequence of non-negative integers
- Choose an integer
. - Replace
with for every ( denotes the bitwise operation).
Find the maximum possible value of
Constraints
Input
Input is given from Standard Input from the following format:
Output
Print the maximum possible value of
Sample Input 1
5
1 2 3 4 5
Sample Output 1
19
Here is a sequence of operations that achieves
- Initially, the sequence
is . - An operation with
changes it to . - An operation with
changes it to , where .
Sample Input 2
5
10 10 10 10 10
Sample Output 2
50
Doing zero operations achieves
Sample Input 3
5
3 1 4 1 5
Sample Output 3
18
我的笔记
本题中的 "You can do the operation below any number of times (possibly zero)." 和 "Sample 1" 就是个迷惑人的幌子,说是可以进行任意次异或操作,然而结果等价于只进行一次异或操作,因为:
具体到示例
所以该题简化为:有
然后直接暴力求解一个个异或再求和肯定是不可行的,要整体来操作。
本题异或、求和都可以看成按位操作,所以可以直接统计出每一位
代码
#include <bits/stdc++.h>
using namespace std;
int main(void)
{
ios::sync_with_stdio(false);
cin.tie(0);
int N;
cin >> N;
vector<int> A(N);
vector<int> bit(30);
for (int i = 0; i < N; i++)
{
cin >> A[i];
int t = A[i];
for (int i = 0; t; i++, t >>= 1)
{
bit[i] += t & 1;
}
}
long long sum = accumulate(A.begin(), A.end(), 0LL);
for (int i = 0; i < N; i++)
{
long long cur_sum = 0, d = 1;
int t = A[i], bit_sum;
for (int j = 0; j < 30; j++)
{
if (t & 1)
{
bit_sum = N - bit[j];
}
else
{
bit_sum = bit[j];
}
t >>= 1;
cur_sum += d * bit_sum;
d <<= 1;
}
sum = max(sum, cur_sum);
}
cout << sum << endl;
return 0;
}
本文采用 CC BY-SA 4.0 许可,本文 Markdown 源码:Haotian-BiJi