蓝桥杯真题讲解:异或和之和 (拆位、贡献法)
- 一、视频讲解
- 二、正解代码
一、视频讲解
蓝桥杯真题讲解:异或和之和 (拆位、贡献法)
二、正解代码
//拆位考虑
#include<bits/stdc++.h>
#define endl "\n"
#define pb push_back
#define deb(x) cout << #x << " = " << x << '\n';
#define INF 0x3f3f3f3f
#define int long long
using namespace std;void solve()
{int n; cin >> n;vector<int>a(n);for(int i = 0; i < n; i ++){cin >> a[i];}int ans = 0;for(int i = 20; i >= 0; i -- ){int s = 0, n0 = 1, n1 = 0;for(int j = 0; j < n; j ++){int bit = (a[j] >> i) & 1;s += bit;if(s % 2){ans += (1 << i) * n0;n1 ++;}else{ans += (1 << i) * n1;n0 ++;}} }cout << ans << endl;
}signed main()
{ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);int t = 1;//cin >> t;while(t--)solve();
}