Build a tree
Time Limit: 2000/1000 MS (Java/Others) Memory Limit:524288/524288 K (Java/Others)
Total Submission(s): 320 Accepted Submission(s): 95
Problem Description
HazelFan wants to build a rooted tree. The tree hasn nodes labeled 0 ton−1, and the father of the node labeledi is the node labeled ⌊(i−1)/k⌋. 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 thenumber of test cases.
For each test case:
A single line contains two positive integers n,k(1≤n,k≤10181018).
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
【题意】
有一棵n个节点的完全k叉树,求其所有子树(包括根节点)节点数量(包括节点本身)的异或值。
【思路】
容易发现,考虑根的所有孩子,最多只有一个不是满k叉树,我们只要把这个子节点作为临界点,其左边的就是满k叉树,其右边的便是比左边层数小一的满k叉树,那么我们每次只要算出中间这个非满k叉树的节点个数即可,然后对这个孩子进行递归处理。
而其他子树由于是满k叉树,其数量可以提前预处理出来。
PS:k等于1时,树退化为链状,需要特判(暴力打表找规律),否则时间效率低下,会TLE。
具体细节见代码。
#include <cstdio>
#include <string>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 105;
ll n,k;
ll num[maxn];
ll power(ll a, ll n)
{
ll ans=1;
while(n)
{
if(n&1) ans*=a;
a*=a;
n>>=1;
}
return ans;
}
void init(ll k,ll depth) //预处理出完全k叉树前i层节点个数和
{
for(int i=1;i<=depth;i++)
{
num[i]=(power(k,i)-1)/(k-1);
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
ll ans;
scanf("%I64d%I64d",&n,&k);
if(k==1) //特判
{
ll temp=n%4;
if(temp==0)
{
ans=n;
}
else if(temp==1) ans=1;
else if(temp==2) ans=n+1;
else ans=0;
printf("%I64d\n",ans);
continue;
}
int depth=1; //求出树的高度
ll res=n-1;
while(res>0)
{
res=(res-1)/k;
depth++;
}
init(k,depth);
ans=n; //根节点为0的子树
ans^=(n-num[depth-1])&1; //最后一层有几个节点,就异或几个1.
depth--;
ll pos=(n-1-1)/k; //临界点在当前层第pos棵子树上
int now=2; //当前是从下往上第几层
while(depth>1) //depth等于1,即变为以0为根节点的子树时,结束递归
{
ll left=num[depth-1]; //当前层最左边节点的编号
ll right=num[depth]-1; //当前层最右边节点的编号
ll temp1=num[now]; //当前层满k叉树子树节点个数
ll temp2=num[now-1]; //当前层满k叉树层数减1后子树节点个数
if((pos-left)&1) //临界点左边满k叉树的个数为奇数,那么结果异或上节点个数,否则异或相互抵消,不计
{
ans^=temp1;
}
if((right-pos)&1) //同理
{
ans^=temp2;
}
ll cnt=pos;
while(cnt<=(n-1-1)/k) //由于cnt*k+1<=n-1,左边会爆long long,故转化为除法。
{
cnt=cnt*k+1;
}
ans^=num[now-1]+n-cnt; //临界点的子树特殊处理
now++;
depth--;
pos=(pos-1)/k;
}
printf("%I64d\n",ans);
}
return 0;
}