(n&-n) will return least significant bit and adding it to n will clear the first consecutive set bits of n and set the bit after them
then anding this number with (itself -1) will clear the least significant bit again
so now n - (this value) will give the value of the first consecutive set bits
I solved it using recursion and memoizing the results whenever required.
I tried to discover some pattern and what I found is that :
if twos_complement(n) is zero then we have to take xor of it with itself thus reduced the problem of finding answer for (n-1).
Else ,suppose k = complement(n)… Then in the range [k,n] every ith number from starting should be xored with every ith number from ending of this range for maximizing the score.
Thus ,problem then got reduces to finding the answer for (k-1).
It can be proven using bit manipulation concepts that every recursion calls atmost logn time.So,overall time complexity will be O(T*log(MaxN))
If the problem will be of printing the permutation then also it can easily be printed using this logic.
Can someone give me the wrong test case for my code? It passed the sample test cases, and one subtask on submission. I think I am missing some corner case. Link
int calc(int n)
{
if (n == 0ll || n == 1ll)
{
return 0ll;
}
if (n == 2ll || n == 3ll)
{
return 6ll;
}
int bits = 0ll;
int tmp = n;
while (tmp > 0ll)
{
bits++;
tmp >>= 1ll;
}
int c = (1ll << bits);
c -= 2ll;
int ans = c * (c + 1ll);
ans -= ((c + 1ll) * 2ll * (c - n));
return (ans + calc(c - n));
}
// Mitesh Darda
// Work Eveyday Like The Future Self You Desire To Be
#include<bits/stdc++.h>
using namespace std;
vector<int> s;
void fillSquare() {
long long int elemToBePushed = 0;
vector<int> twoPower;
int p = 0;
twoPower.push_back(1);
while (elemToBePushed < 1000000000) {
elemToBePushed += twoPower[p];
twoPower.push_back(twoPower[p] * 2);
s.push_back(elemToBePushed);
p++;
}
}
void solve() {
long long n; cin >> n;
long long ans = 0;
vector<bool> check(n + 1, true);
for (int i = n; i >= 1; --i) {
if (check[i]) {
auto upper = lower_bound(s.begin(), s.end(), i);
int num = s[upper - s.begin()] - i;
if (num == 0)continue;
ans += (num ^ i) * 2;
check[num] = false;
}
}
cout << ans << endl;
}
int main()
{
fillSquare();
int t; cin >> t;
while (t--) {
solve();
}
return 0;
}
i have done this problem in O(n) still it is giving me TLE(1.010000) for the last 5 test cases can someone explain me what i am doing wrong ?