題意: 現有一個數組a,選兩個不同下標的數一個賦值爲二者的 ’ & ‘值,另一個賦值爲二者的’ | '值。最後計算所以ai ^ 2的和ans,求ans的最大值。
思路:
- 1的個數不會變:例如3 和 5,011 & 101 = 001,而011 | 101 = 111;第一位的1,第二位的1,第三位的1的個數都沒有變,只是在各個數之間移動(意味着所有數的和不會改變)。
- 因爲(a + b) ^ 2 >= a ^ 2 + b ^ 2,所以我們可以大膽處理直接得到答案
- 讓有限的1分配給經量少的數,即同過每個位置上的1在各個數間的移動,使得某個(或些)數經量大,這樣取平方後得到的答案就會是max。
代碼實現:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cctype>
#include <cstring>
#include <iostream>
#include <sstream>
#include <string>
#include <list>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <functional>
#define endl '\n'
#define null NULL
#define ll long long
#define int long long
#define pii pair<int, int>
#define lowbit(x) (x &(-x))
#define ls(x) x<<1
#define rs(x) (x<<1+1)
#define me(ar) memset(ar, 0, sizeof ar)
#define mem(ar,num) memset(ar, num, sizeof ar)
#define rp(i, n) for(int i = 0, i < n; i ++)
#define rep(i, a, n) for(int i = a; i <= n; i ++)
#define pre(i, n, a) for(int i = n; i >= a; i --)
#define IOS ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);
const int way[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
using namespace std;
const int inf = 0x7fffffff;
const double PI = acos(-1.0);
const double eps = 1e-6;
const ll mod = 1e9 + 7;
const int N = 2e5 + 5;
int n, ans, a[N], c[N];
signed main()
{
cin >> n;
for(int i = 0; i < n; i ++){
int x, cnt = 0; cin >> x;
while(x){
c[cnt] += x & 1; //統計所有數第cnt位有多少個1
cnt ++;
x >>= 1;
}
}
for(int i = 0; i <= 20; i ++)
for(int j = 0; j < c[i]; j ++)
a[j] += (1 << i); //每次都會從a[0]開始分配,所以a[0]將會是最大的一個數
for(int i = 0; i < n; i ++)
ans += a[i] * a[i];
cout << ans << endl;
return 0;
}