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
思路:
性质:在整颗树中,最多只有一颗树不是满二叉树。
所以只要找到是哪棵子树不是满二叉树,以那棵子树作为整棵树求它的异或和,很显然子树也具有一样的性质,这样就可以递归求解,求出来之后直接异或其它所有满二叉树的大小就是答案,注意别忘记异或上n。
而当除开这颗树的其他满二叉树,如果这棵树的个数是奇数,那么就异或一次这颗子树的大小,偶数就不用了,(异或的性质)。而如果当k是奇数的话,我们还要对这颗树的的一颗子树去深搜一次(如果是偶数的话,那么所有子树的结构相同,偶数次异或,答案不变)。然后异或一次子树的大小。
最后,当 k = 1的时候,这颗树就变成了一条链,那么此时的答案就是n^(n-1)^(n-2)...^1.
那么对于n的前缀异或和满足一个规律,那就是用这个数模上4,如果数是1,那么答案是1
如果数是2,答案是n+1,如果数是3,答案是0,如果数是0,答案是n。那么这样的话,这题答案就很简单了。
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <vector>
#define siz 505
#define LL long long
using namespace std;
LL n,m;
int p[100];
LL ans = 0;
void dfs(LL now)
{
//ans ^= now;
if(now == 1) return ;
LL tx = (now - 1)/m;//一颗子树的大小
ans ^= tx;//答案异或
dfs(tx);
}
void solve()
{
while(1)
{
if(n-1<=m)
{
if(n%2==0) ans^=1;//cout<<ans<<"%%%%%%%%%"<<endl;
break;
}
LL x = 1,now = 1;
while(now+x*m<n)//最大的满树
{
x*=m;
now+=x;//
}
LL l = (n - now - 1)/x;//剩余的节点最多能构成几个满二叉树
LL r = m - l - 1;//另外一边的满二叉树(假如没有不是满的二叉树,我们可以假设一颗满树不是满二叉树)。
if(l%2==1)
{
ans^=now;//异或答案
// dfs()
if(m%2==1)//奇数深搜答案,
dfs(now);
}
if(r%2==1)
{
ans^=(now-x);
if(m%2==1)
dfs(now-x);
}
n-=(l*now+r*(now-x)+1);//不是满的二叉树的大小
ans^=n;
}
printf("%lld\n",ans);
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%lld%lld",&n,&m);
if(m==1)
{
int t = n % 4;
if(t==1)
{
printf("1\n");
}
else if(t==2)
{
printf("%lld\n",n+1);
}
else if(t==3)
{
printf("0");
}
else if(t==0) printf("%lld\n",n);
continue;
}
ans = n;
solve();
}
return 0;
}
/*
8 3
15
13 3
5
*/