Build a tree
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 524288/524288 K (Java/Others)Total Submission(s): 1204 Accepted Submission(s): 493
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个点的有根数,根编号为0,i号节点的父亲是(i-1)/k号节点
求出所有子树大小的异或和
性质:对于一颗满k叉树而言,如果k是偶数,那么它的异或和就是树的大小
如果k是奇数,那么它的异或和就是任意一棵子树大小的异或和再异或树的大小
而这题的树也有几个性质:
①假设n足够大,那么根有k个儿子(废话)
②这k棵子树最多只有一棵不是满二叉树
那么假设k不等于1,二叉树的深度不会超过63
所以只要找到是哪棵子树不是满二叉树,以那棵子树作为整棵树求它的异或和,很显然子树也具有一样的性质,这样就可以递归求解,求出来之后直接异或其它所有满二叉树的大小就是答案,注意别忘记异或上n
还有k=1要特判
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cmath>
#include<set>
using namespace std;
typedef long long int ll;
const int N = 2e5+5;
ll ans=0,n,k;
void solve()
{
ans=n;
while(1) //通过不断删树,使得最后的的非满子树变成一个2层的树
{ //每一次计算除掉那棵非满子树外的其他树的异或和
if(n-1<=k) //若树删减到只有两层的情况时
{
if((n-1)%2)
ans^=1; //ans已经异或过根节点了
break;
}
ll now,x,res;
now=x=res=1; //now当前节点数总和,x表示当前层总的节点数
while(0<=now+x*k&&now+x*k<n)
{
x=x*k;
now+=x;
res^=now;
}
//now表示现在除最底层外其他节点的节点数,x表示now表示的层的节点数
ll l,r;// l表示在那棵非满子树左边有多少棵子树,r同理
l=(n-now-1)/x;
r=k-1-l;
if(k%2)
{
if(l%2) ans^=res;
if(r%2) ans^=res^(now-x);
}
else
{
if(l%2) ans^=now;
if(r%2) ans^=(now-x);
}
n-=l*now+1+r*(now-x); //将已经计算过的树删掉,只留下那个非满二叉树
ans^=n; //异或删完之后的根节点
}
}
int main() {
int t;
ll i;
scanf("%d",&t);
while(t--)
{
scanf("%lld%lld",&n,&k);
if(k==1)
{
if(n%4==1) printf("%lld\n",1);
else if(n%4==2) printf("%lld\n",n+1);
else if(n%4==3) printf("%lld\n",0);
else printf("%lld\n",n);
}
else
{
solve();
printf("%lld\n",ans);
}
}
return 0;
}