You can practice the problem here.
Problem
An array a[0], a[1], ... , a[n - 1] of nonnegative integer numbers is said to be good if
a[0] + a[1] + ... + a[n - 1] = 2 * (a[0] ^ a[1] ^ ... ^ a[n - 1])
Given that an array of length n, append at most 3 elements to it to make it good.
Solution
Let S be the sum of the array, which is a[0] + a[1] + ... + a[n - 1] and X be their XOR value. Then we'll have
S = 2 * X
A simple solution here is to add X and X + S to the array.
S = 2 * X
S + X + (X + S) = 2 * (X ^ X ^ (X + S)) // X ^ X = 0
2 * (X + S) = 2 * (X + S)
C++ Implementation
ll S = 0, X = 0;
REP(i, n) {
ll a; cin >> a;
S += a;
X ^= b;
}
cout << 2 << "\n";
cout << X << " " << X + S << "\n";
No comments:
Post a Comment