hdu 6121(Build a tree) 瞎搞+麻烦

本文介绍了一种解决给定K叉树所有子树大小异或和问题的算法实现,通过递归计算不平衡K叉树的子树大小,并使用位运算完成异或操作,适用于计算机科学中的数据结构与算法研究。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:点击打开链接

题目大意:给定一棵有n个结点的k叉树,求所有子树的大小的异或和~~~

多校补题日记~~~


#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
typedef long long llt;
llt SIZE[100];
llt L[100];
//完全k叉树
llt complete(llt n,int depth,int k)
{
    if((k&1)==0) return n;
    else
    {
        llt ans=0;
        for(int i=1;i<=depth;i++)
            ans^=SIZE[i];
        return ans;
    }
}
//不平衡的k叉树
llt dfs(llt n,int depth,int k)
{
    llt ret=n;
    llt rem=n-SIZE[depth];
    if(rem%L[depth]==0)
    {
        llt comp=rem/L[depth];
        if(comp&1) ret^=complete(SIZE[depth],depth,k);
        if((k-comp)&1) ret^=complete(SIZE[depth-1],depth-1,k);
        return ret;
    }
    else
    {
        llt comp=rem/L[depth];
        llt cut=rem%L[depth];
        if(comp&1) ret^=complete(SIZE[depth],depth,k);
        if((k-comp-1)&1) ret^=complete(SIZE[depth-1],depth-1,k);
        return ret^dfs(SIZE[depth-1]+cut,depth-1,k);
    }
}
int main()
{
    int t;
    scanf("%d",&t);

    while(t--)
    {
    	llt n,k;
    	scanf("%lld%lld",&n,&k);
        if(k==1)
        {
            if(n%4==1) printf("%d\n",1);
            else if(n%4==2) printf("%d\n",n+1);
            else if(n%4==3) printf("%d\n",0);
            else printf("%d\n",n);
            continue;
        }
        int depth=1;
        llt sum=1,left=k;
        L[1]=1;
        while(sum+left<=n)
        {
        	SIZE[depth]=sum;
        	L[++depth]=left;
        	sum+=left;
			left*=k;
        }
        SIZE[depth]=sum;
        if(sum==n) printf("%lld\n",complete(n,depth,k));
        else printf("%lld\n",dfs(n,depth,k));
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值