Build a tree
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 524288/524288 K (Java/Others)Total Submission(s): 937 Accepted Submission(s): 366
Problem Description
HazelFan wants to build a rooted tree. The tree has
n
nodes labeled
0
to
n−1
, and the father of the node labeled
i
is the node labeled
⌊i−1k⌋
. 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)
, denoting the number of test cases.
For each test case:
A single line contains two positive integers n,k(1≤n,k≤1018) .
For each test case:
A single line contains two positive integers n,k(1≤n,k≤1018) .
Output
For each test case:
A single line contains a nonnegative integer, denoting the answer.
A single line contains a nonnegative integer, denoting the answer.
Sample Input
2 5 2 5 3
Sample Output
7 6
参考题解 http://blog.csdn.net/hackertom/article/details/77199170
/*
题意:
n个节点的k叉树,每个子树异或起来结果是多少
解题思路
最后一个节点左边全是depth层满k叉树,右边全是depth-1层满k叉树
那么我们就可以倒着枚举每个子树,先处理特殊的再处理有规律的,详见代码注释
这里我总结了一下满k叉树的一些性质,见上图
*/
#include <cstdio>
using namespace std;
const int maxn = 100;
typedef long long ll;
ll sum[maxn];///前i层共多少节点
ll n,k;
ll pow(ll x,ll n){
ll res = 1;
while(n>0){
if(n&1) res *= x;
x = x*x;
n >>= 1;
}
return res;
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
ll ans = 0;
scanf("%lld%lld",&n,&k);
///k=1特殊情况,规律是打表找出来的
if(k==1){
int res = n%4;
if(res==0) ans = n;
else if(res==1) ans = 1;
else if(res==2) ans = n+1;
else ans = 0;
printf("%lld\n",ans);
continue;
}
///根是第一层
int depth = 1;
ll m = n-1;
///求层数
while(m>0){
m = (m-1)/k;
depth++;
}
///预处理sum数组。
for(int i = 0;i<=depth;++i){
sum[i] = (pow(k,i)-1)/(k-1);///等比数列求和公式提出负号
}
///整棵树
ans = n;
///先处理最后一层
ans ^= (n-sum[depth-1])&1;///&1用来区分奇偶性
--depth;///从倒数第二层开始处理
ll p = ((n-1)-1)/k;///最后一个点的父亲的编号
ll lchild,rchild,lnum,rnum,leftchild;
for(int d = 2;p>0;p=(p-1)/k,++d,--depth){
lchild = sum[depth-1];///当前层最左节点编号
rchild = sum[depth] - 1;///当前层最右节点编号
lnum = sum[d];///p左边的树是满d层k叉树
rnum = sum[d-1];///p右边是满d-1层k叉树
if((p-lchild)&1) ans ^= lnum;
if((rchild-p)&1) ans ^= rnum;
leftchild = p;
///找到以p为根节点,最左边的子节点
while(leftchild<=(n-1-1)/k) leftchild = leftchild*k+1;
leftchild = n-leftchild;
ans ^= sum[d-1]+leftchild;
}
printf("%lld\n",ans);
}
return 0;
}