HDU 5573 Binary Tree(找规律)
2015-12-02 10:27
399 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5573
题意:给你一个完全二叉树,节点为自然数的排列(第一行1,第二行2 3,第三行4 5 6 7。。。)。现在,给你一个N和K,K表示给你这个完全二叉树的前K行,从第1行到第K行有很多路径,希望找到一条路径能表示N,路径上的节点可取正也可取负,要求最后的和为N。
思路:由题目给的数据范围可知前两个节点有一个一定可以表示N。(前两个节点可以表示1 - 2^k)
code:
题意:给你一个完全二叉树,节点为自然数的排列(第一行1,第二行2 3,第三行4 5 6 7。。。)。现在,给你一个N和K,K表示给你这个完全二叉树的前K行,从第1行到第K行有很多路径,希望找到一条路径能表示N,路径上的节点可取正也可取负,要求最后的和为N。
思路:由题目给的数据范围可知前两个节点有一个一定可以表示N。(前两个节点可以表示1 - 2^k)
code:
#include <cstdio> #include <cmath> using namespace std; const int MAXN = 65; typedef long long LL; struct node { LL value; char ch; }; node rec[MAXN]; void solve(LL p, LL N) { int L = 1; while (true) { if (N < 0) { rec[L].value = p; rec[L++].ch = '-'; N += p; p >>= 1; } else if (N > 0) { rec[L].value = p; rec[L++].ch = '+'; N -= p; p >>= 1; } else return; } } int main() { int T; scanf("%d", &T); for (int cas = 1; cas <= T; ++cas) { LL N; int K; scanf("%lld %d", &N, &K); LL p = (LL)pow(2L, K - 1) + 1; if (N & 1) --p; solve(p, N); printf("Case #%d:\n", cas); for (int i = K; i >= 1; --i) { printf("%lld %c\n", rec[i].value, rec[i].ch); } } return 0; }
相关文章推荐
- 设置HTML的font-zise,使rem更好的兼容移动端
- codeforces 472BDesign Tutorial: Learn from Life(简单贪心)
- js数组方法
- linux查看硬件信息命令和教程详解
- SharePoint网站集功能介绍
- 使用正则表达式匹配任意字符包括空格和换行符
- mongodb配置文件详解
- Hadoop DataNode与DFSClient交互
- 深度学习-人脸识别
- iOS开发 -- 字符串删除某些元素的方法
- cxf .jar 包 冲突 setXmlStandalone(Z)V
- Android视频播放器之学习MediaPlayer
- 安卓ListView中嵌套ListView导致外层ListView的ItemOnclick方法无法响应的解决办法
- System.loadLibrary()的使用方法汇总
- nginx优化 突破十万并发
- 最大公约数
- Java String操作 trim()
- LeetCode 151 Reverse Words in a String
- c++多态实现的机制
- Unix Network Programming(6)---套接字地址结构