[CF750G]New Year and Binary Tree Paths
2017-09-14 17:20
323 查看
题目大意
一颗无穷个节点的完全二叉树,编号满足线段树分配。求有多少条树上的简单路径编号和为s?
结论
从根节点到一个编号为x的节点,到根编号和为2x-bitcount(x)。用归纳法证明。
我们尝试枚举这条简单路径两个节点到lca分别的距离为a和b,设lca为x。
首先一定有x∗(2a+1+2b+1−3)的编号和。
然后我们尝试把x子树所有编号都去掉x的贡献(不是减x,而是第一层-x,第二层-2x,第三层-4x,以此类推)。
容易发现新的这棵树中还满足一个编号为x的节点,到根编号和为2x-bitcount(x)。
然后我们知道x∗(2a+1+2b+1−3)+k=s
k表示其他的贡献。
容易讨论k的取值范围在[2b−1,2a−a+2b+1−b−3]。
讨论过程可以默认a>0,b>0然后发现a=0或b=0代入此式仍然是对的。最小值就是两边都往左最大值就是两边都往右。
k的最大值严格比2a+1+2b+1−3小,这意味着如果存在一个x能找到一个合法k,那么x+1或-1都不可能再有合法k(即s−x∗(2a+1+2b+1−3)不在k的取值范围内)。
然后我们唯一确定这个x后,问题得到转化。
找到两个数p<2a−1以及q<2b
使得2∗(p+q)−bitcount(p)−bitcount(q)=s−x∗(2a+1+2b+1−3)
其中q的第b-1位必须是1。
然后我们可以枚举bitcount的和,这样就可以确定p+q的值。
于是我们进行数位DP,注意到p和q的上界刚好是2的次幂-1,所以这个数位DP不需要别的东西(如常见的和上界比较的维),然后因为和确定了,因此只要让每一位严格等于和的那一位即可,而不需要专门开一维记录,只需要用一维记录是否进位即可。
#include<cstdio> #include<algorithm> #define fo(i,a,b) for(i=a;i<=b;i++) using namespace std; typedef long long ll; const int maxd=58; ll f[maxd+10][maxd*2+10][2],two[maxd+10]; int i,j,k,l,t,n,m,a,b; ll x,y,now,s,ans; void work(int a,int b,ll now,int cnt){ int i,j,k,l,r,t,s,d,mx=max(a-2,b-1)+2; fo(i,0,maxd+2) fo(j,0,cnt) f[i][j][0]=f[i][j][1]=0; f[0][0][0]=1; fo(i,0,mx-1){ if ((now&two[i])) d=1;else d=0; fo(j,0,cnt) fo(t,0,1) if (f[i][j][t]){ fo(l,0,1) fo(r,0,1){ if (l&&i>a-2) continue; if (r&&i>b-1) continue; if (!r&&i==b-1) continue; s=l+r+t; k=s/2;s=s%2; if (s!=d) continue; f[i+1][j+l+r][k]+=f[i][j][t]; } } } ans+=f[mx][cnt][0]; } int main(){ two[0]=1; fo(i,1,maxd+1) two[i]=two[i-1]*2; scanf("%I64d",&s); fo(a,0,maxd) fo(b,0,maxd){ y=two[a+1]+two[b+1]-3; x=s/y; while (x){ now=s-x*y; if (now>two[a]-a+two[b+1]-b-3){ x=0; break; } if (now>=two[b]-1&&now<=two[a]-a+two[b+1]-b-3) break; x--; } if (!x) continue; now=s-x*y; fo(i,0,maxd*2) if ((now+i)%2==0) work(a,b,(now+i)/2,i); } printf("%I64d\n",ans); }
相关文章推荐
- [CodeForces750G]New Year and Binary Tree Paths
- CodeForces 750G. New Year and Binary Tree Paths
- Insertion Sort List and Binary Tree Paths
- CF #611 H, New Year And Forgotten Tree - 匹配 | Hall定理
- Construct Binary Tree from Preorder and Inorder Traversal
- [leetcode] 257. Binary Tree Paths
- 257. Binary Tree Paths
- Minimum Depth of Binary Tree and quick sort
- 257. Binary Tree Paths
- CodeForces 611 C. New Year and Domino(dp+容斥)
- Binary Search Tree--find Lowest Common Ancestor--C++ and Java
- construct-binary-tree-from-preorder-and-inorder-traversal
- Lintcode72 Construct Binary Tree from Inorder and Postorder Traversal solution 题解
- 【LeetCode笔记】Construct Binary Tree from Preorder and Inorder Traversal 前序、中序还原二叉树
- Construct Binary Tree from Inorder and Postorder Traversal
- 【Educational Codeforces Round 6E】【线段树 dfs序】New Year Tree 子树颜色修改子树颜色数
- LeetCode题解:Binary Tree Level Order Traversal I and II
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal
- 105. Construct Binary Tree from Preorder and Inorder Traversal