hdu 6121 Build a tree (图论)
来源:互联网 发布:农村淘宝店开店条件 编辑:程序博客网 时间:2024/06/07 14:04
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 integersn,k(1≤n,k≤1018) .
For each test case:
A single line contains two positive integers
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
25 25 3
Sample Output
76
题意:有一棵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
- hdu 6121 Build a tree (图论)
- hdu 6121 Build a tree (模拟)
- HDU 6121 Build a tree (技巧)
- HDU 6121 Build a tree(递归)
- HDU 6121 Build a tree
- hdu 6121 Build a tree
- hdu 6121 Build a tree
- HDU 6121Build a tree
- hdu--6121--Build a tree
- hdu--6121:Build a tree
- hdu 6121 Build a tree
- HDU-6121 Build a tree
- hdu 6121 Build a tree
- HDU 6121 Build a tree【】
- HDU 6121 Build a tree [想法题]
- HDU 6121 Build a tree [想法题]
- hdu 6121(Build a tree) 瞎搞+麻烦
- HDU 6121 Build a tree(找规律+implement)
- Java——Java集合Collections工具类
- List User Messages:列出用户消息
- 史上最全的 struts2 面试题
- cocos2dx-lua绑定自定义c++类(一)
- springboot整合swagger
- hdu 6121 Build a tree (图论)
- 链家笔试题总结
- mysql 存储过程及事务实例
- RPC原理
- CSS布局模型----第八系列
- C语言指针和数组
- 学生做国际义工:时尚背后有多少坑
- 2.1 Hello Unity
- 计算矩阵边缘元素之和 (Coursera 程序设计与算法 专项课程2 C程序设计进阶 李戈;OpenJudge)