HazelFan wants to build a rooted tree. The tree has nn nodes labeled 0 to n−1, and the father of the node labeled i is the node labeled 

. HazelFan wonders the size of every subtree, and you just need to tell him the XOR value of these answers.


Input

The first line contains a positive integer T(1≤T≤5)T(1≤T≤5), denoting the number of test cases. 
For each test case: 
A single line contains two positive integers n,k(1≤n,k≤1018)n,k(1≤n,k≤1018). 
Output

For each test case: 
A single line contains a nonnegative integer, denoting the answer.Sample Input

2
5 2
5 3

Sample Output

7
6 题意:画一下题目介绍的树,发现这是一个k叉树,那么题目要求所有子树大小的异或和。
思路:我们从序号为n的节点开始,往上求异或和。n计算到某一层时,对于处在n节点左边的节点(子树),它们是t+1层的满k叉树,在右边的节点(子树)是t层的满二叉树,
满二叉树的大小可以通过打表得到。根据异或计算的性质,大小相同的子树进行异或,有奇数个进行异或时结果为该子树的大小,偶数个时为0。
而对n位置节点的子树来说,不是满二叉树就是非满二叉树,而且在计算这个子树大小时一旦它在某一层是非满二叉树,接下来往上它就一直是非满二叉树。
还有,k==1时特判一下。
具体实现参看代码。 AC代码:
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
typedef long long LL;
LL n, k;
LL num[];
int main()
{
int T;
cin>>T;
num[]=;
while(T--)
{
scanf("%lld %lld", &n, &k);
if(k==){
if(n==)
printf("%d\n", );
else if(n==)
printf("%d\n",);
else if(n==)
printf("%d\n", );
else
{
int k=n%;
if(k==)
printf("%lld\n", n);
else if(k==)
printf("%d\n", );
else if(k==)
printf("%lld\n", n+);
else
printf("%d\n", );
}
continue;
}
n--;
int level=,t=;
LL lm=, rm=;
while(rm<n){
t++;
lm=rm+;
rm=lm*k;
num[t]=rm+;
}
LL res=,left,right,s=n+,m;
t=;
bool flag=;
LL mid=n%k;//mid判断是否为满k叉树, m为非满k叉树的大小
left=n-mid-lm+;
//cout<<left<<endl;
if(left&){
res^=num[];
}
if(mid&)
res^=num[];
if(mid)
flag=; m=(n-(n-)/k*k)*num[]+;
//cout<<m<<endl;
while(n)
{ //cout<<res<<'*'<<endl; t++;
//cout<<t<<' '<<m<<endl; n=(n-)/k;
if(n<=)
break; mid=n%k;
lm=(lm-)/k;
rm=(rm-)/k;
//cout<<lm<<' '<<n<<' '<<rm<<endl;
right=rm-n;
left=n-lm+;
if(flag||mid){
flag=;
left--;
res^=m;
} if(left&)
res^=num[t];
if(right&)
res^=num[t-];
m+=(n-(n-)/k*k-)*num[t]+(((n-)/k+)*k-n)*num[t-]+; }
res^=s;
printf("%lld\n", res);
}
return ;
}

												

最新文章

  1. Java学习笔记(二)
  2. BZOJ 4668: 冷战
  3. iOS 关于修饰代理用weak还是assign
  4. 闭包-&gt;类的实例数组排序
  5. Nhiberate (二) 搭项目
  6. Bring Your Charts to Life with HTML5 Canvas and JavaScript
  7. PROTEL99生成GERBER的操作说明
  8. 冒泡排序算法(Java)
  9. Ubuntu将新增磁盘挂载到home下
  10. c# networkcomms 3.0实现模拟登陆总结
  11. [CF932E]Team Work &amp; [BZOJ5093]图的价值
  12. 手把手图文教你从Eclipse项目迁移Android Studio
  13. Postgresql查询出换行符和回车符:
  14. Petrozavodsk Winter-2018. Jagiellonian U Contest
  15. django RESTful设计方法
  16. Python全栈之路----函数----返回值
  17. cesium相机绕点飞行
  18. 洛谷P1973 [NOI2011]Noi嘉年华(动态规划,决策单调性)
  19. 24款最好的jQuery日期时间选择器插件
  20. zabbix 监控Nginx和PHP

热门文章

  1. String 与StringBuffer习题
  2. 测开之路七十七:shell之if、case、for、while
  3. hibernate搭建及其增删改查
  4. Kestrel web server implementation in ASP.NET Core
  5. 【SD系列】SAP SD模块-创建供应商主数据BAPI
  6. python中进程池和回调函数
  7. tensorflow学习框架(炼数成金网络版学习记录)
  8. 在Eclipse的kepler中执行OSGIproject出错的解决方式
  9. 问题处理——&quot;无法导航到插入符号下的符号&quot;
  10. idea 配置maven web项目