Codeforces Tricky Sum

//Next Codeforces Round #354 (Div. 2)
#include<bits/stdc++.h>

//#include<cstdio>
//#include<iostream>
//#include<algorithm>
//#include<vector>
//#include<cstring>
//#include<cmath>
//#include<map>

using namespace std;

#define fast ios_base::sync_with_stdio(false)
#define bfast cin.tie(0)
#define outs(x) cout << x << " "
#define outn(x) cout << x << "\n"
#define sf scanf
#define pf printf
#define nl puts("")
#define psb push_back
#define high 45

typedef long long LL;
typedef vector<int>vii;
typedef vector<LL>vll;

struct my
{
    LL p, psum;
};

my ar[high];

void store()
{
    int i=0;

    ar[0].p = 1;
    ar[0].psum = -1;

    for(i=1; i<35; i++)
    {
        ar[i].p = powl(2 , i);
        ar[i].psum = ar[i-1].psum - ar[i].p;
    }

    //for(i=0; i<35; i++) cout << ar[i].p << " " << ar[i].psum << "; ";
}

int khoj(int lo, int hi, int itm)
{
    int mid;

    while(lo <= hi)
    {
        mid = (lo + hi) / 2;

        if(ar[mid].p == itm) return mid;
        else if(ar[mid].p > itm) hi = mid - 1;
        else if(ar[mid].p < itm) lo = mid + 1;
    }

    return lo;
}

int main()
{
    fast;
    store();
    int t ;
    LL n , in , i, Gsum=0 , ans=0;
    cin >> t;
    while(t--)
    {
        cin >> n;

        in = khoj(0 , 34, n);

        if(ar[in].p != n)
        {
            in--;
        }

        //cout << ar[in].p << " " << ar[in].psum << "\n";

        Gsum = (n * (n + 1)) / 2;

        ans = (Gsum + ar[in].psum) + ar[in].psum;

        cout << ans << "\n";
    }

    return 0;
}

Comments

Popular posts from this blog

SPOJ-CMG - Collecting Mango

LightOJ 1009 - Back to Underworld

LeetCode Palindrome Number