hdu 6121 Build a tree (图论)

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 n1 , and the father of the node labeled i is the node labeled i1k . 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(1T5) , denoting the number of test cases.
For each test case:
A single line contains two positive integers
n,k(1n,k1018) .
 

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个点的有根数,根编号为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;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值