思路是利用以下恒等式:
x + y = (x xor y) + 2 × (x and y)
所以每次操作的花费为
cost = 2×(x and y) = x + y − (x xor y)
经过 n−1 次操作后,数组中剩下的最终美食为所有初始食物的 xor,记为 X;
而初始总和为 S,则总花费为 S − X。
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define endl "\n"
signed main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
int totalSum = 0, totalXor = 0;
for(int i = 0; i < n; i++){
int x;
cin >> x;
totalSum += x;
totalXor ^= x;
}
cout << (totalSum - totalXor) << endl;
return 0;
}