Build a tree
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 524288/524288 K (Java/Others)Total Submission(s): 781 Accepted Submission(s): 285
For each test case:
A single line contains two positive integers n,k(1≤n,k≤1018).
A single line contains a nonnegative integer, denoting the answer.
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll quick(ll a,ll b)
{
ll ret=1;
while(b)
{
if(b&1)
ret*=a;
b>>=1;
a*=a;
}
return ret;
}
int main()
{
// int s=1;
// for(int i=2; i<20; i++)
// s^=i,printf("%d %d\n",i,s);
int t;
scanf("%d",&t);
while(t--)
{
ll n,k;
scanf("%I64d%I64d",&n,&k);
if(k==1)
{
if(n%4==0)
printf("%I64d\n",n);
else if(n%4==1)
{
printf("1\n");
}
else if(n%4==2)
printf("%I64d\n",n+1);
else
printf("0\n");
continue;
}
ll ans=1,h=0,anss=1;
while(n>=anss)
{
ans*=k;
anss+=ans;
h++;
}
ll yu=n-(anss-ans),sum,w=k;
if(yu&1)
sum=1;
else
sum=0;
ll t=1;
ll cun=k;
for(ll i=h; i>0; i--)
{
ll geshu=quick(k,i-1);
ll duo=yu/w;
ll zhong =yu-duo*w;
ll r=geshu-duo-1;
ll tt=t+w;
ll ttt=t+zhong;
if(duo&1)
sum^=tt;
sum^=ttt;
if(r&1)
sum^=(t);
// if(!t)
// t=1;
t+=cun;
cun*=k;
w*=k;
}
printf("%I64d\n",sum);
}
}