zoukankan      html  css  js  c++  java
  • HDU 5573 Binary Tree(找规律)

    题目链接: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 #include <cstdio>
     2 #include <cmath>
     3 using namespace std;
     4 const int MAXN = 65;
     5 typedef long long LL;
     6 
     7 struct node
     8 {
     9     LL value;
    10     char ch;
    11 };
    12 node rec[MAXN];
    13 void solve(LL p, LL N)
    14 {
    15     int L = 1;
    16     while (true) {
    17         if (N < 0) {
    18             rec[L].value = p;
    19             rec[L++].ch = '-';
    20             N += p;
    21             p >>= 1;
    22         } 
    23         else if (N > 0) {
    24             rec[L].value = p;
    25             rec[L++].ch = '+';
    26             N -= p;
    27             p >>= 1;
    28         }
    29         else return;
    30     }
    31 }
    32 
    33 int main() 
    34 {
    35     int T;
    36     scanf("%d", &T);
    37     for (int cas = 1; cas <= T; ++cas) {
    38         LL N;
    39         int K;
    40         scanf("%lld %d", &N, &K);
    41         LL p = (LL)pow(2L, K - 1) + 1;
    42         if (N & 1) --p;
    43         solve(p, N);
    44         printf("Case #%d:
    ", cas);
    45         for (int i = K; i >= 1; --i) {
    46             printf("%lld %c
    ", rec[i].value, rec[i].ch);
    47         }
    48     }
    49     return 0;
    50 }
  • 相关阅读:
    POJ 1659 Frogs' Neighborhood
    zoj 2913 Bus Pass(BFS)
    ZOJ 1008 Gnome Tetravex(DFS)
    POJ 1562 Oil Deposits (DFS)
    zoj 2165 Red and Black (DFs)poj 1979
    hdu 3954 Level up
    sgu 249 Matrix
    hdu 4417 Super Mario
    SPOJ (BNUOJ) LCM Sum
    hdu 2665 Kth number 划分树
  • 原文地址:https://www.cnblogs.com/ykzou/p/5012195.html
Copyright © 2011-2022 走看看