本文共 2549 字,大约阅读时间需要 8 分钟。
Gottfried learned about binary number representation. He then came up with this task and presented it to you.
You are given a collection of nn non-negative integers a1,…,ana1,…,an. You are allowed to perform the following operation: choose two distinct indices 1≤i,j≤n1≤i,j≤n. If before the operation ai=xai=x, aj=yaj=y, then after the operation ai=x AND yai=x AND y, aj=x OR yaj=x OR y, where ANDAND and OROR are bitwise AND and OR respectively (refer to the Notes section for formal description). The operation may be performed any number of times (possibly zero).
After all operations are done, compute ∑ni=1a2i∑i=1nai2 — the sum of squares of all aiai. What is the largest sum of squares you can achieve?Input
The first line contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105).
The second line contains nn integers a1,…,ana1,…,an (0≤ai<2200≤ai<220).Output
Print a single integer — the largest possible sum of squares that can be achieved after several (possibly zero) operations.ExamplesinputCopy
1123
outputCopy
15129
inputCopy
31 3 5
outputCopy
51
inputCopy
2349525 699050
outputCopy
1099509530625
Note
In the first sample no operation can be made, thus the answer is 12321232.
In the second sample we can obtain the collection 1,1,71,1,7, and 12+12+72=5112+12+72=51.
If xx and yy are represented in binary with equal number of bits (possibly with leading zeros), then each bit of x AND yx AND y is set to 11 if and only if both corresponding bits of xx and yy are set to 11. Similarly, each bit of x OR yx OR y is set to 11 if and only if at least one of the corresponding bits of xx and yy are set to 11. For example, x=3x=3 and y=5y=5 are represented as 01120112 and 10121012 (highest bit first). Then, x AND y=0012=1x AND y=0012=1, and x OR y=1112=7x OR y=1112=7.
这题有两个要点:
一个是x+y=x&y+x|y;这个条件可以启发我们和不变,也就是说总和不变,想使ai^2的总和最大。
考虑只有a和b两个数的情况,设总和为s,那么a^2+b^2=(a^2)+(s-a)^2——-展开化简可以知道是二次函数,取到极端是最大的。那么多个的类推过去
另一个结论就是每一位上的1的个数不变。也就是说当前位是1或者是0,和0或者1,1或者0进行&和|操作,最后该位上的1的个数不变。
那么两点结合,根据贪心,统计每一位上1的个数,有1就尽量放就可以了
#include<iostream>#include<vector>#include<queue>#include<cstring>#include<cmath>#include<cstdio>#include<algorithm>using namespace std;const int maxn=2e5+100;typedef long long LL;LL cnt[22];int main(void){ cin.tie(0);std::ios::sync_with_stdio(false); LL n;cin>>n; for(LL i=1;i<=n;i++){ LL x;cin>>x; for(LL j=0;j<20;j++){ cnt[j]+=(x>>j)&1; } } LL sum=0; for(LL i=1;i<=n;i++){ LL ans=0; for(LL j=0;j<20;j++){ if(cnt[j]){ cnt[j]--; ans+=(1<<j); } } sum+=ans*ans; } cout<<sum<<endl;return 0;}
转载地址:http://ildt.baihongyu.com/