• UVa712 S-Trees


    // UVa712 S-Trees
    // Rujia Liu
    // 题意:给一棵满二叉树,每一层代表一个01变量,取0时往左走,取1时往右走。给出所有叶子的值,以及一些查询(即每个变量的值),求最后到达的叶子的值
    // 算法:结点从上到下编号为1, 2, 3, ...则左走就是乘以2,右走是乘以2加1。第一个叶子的编号是2^n
    #include<iostream>
    #include<string>
    using namespace std;
    
    const int maxn = 10;
    int n, v[maxn];//映射表
    string leaves;
    
    int solve(const string& q) {
      int u = 1;
      for(int i = 0; i < n; i++) {
        if(q[v[i]] == '0') u *= 2; else u = u*2+1;
      }
      return leaves[u-(1<<n)] - '0';
    }
    
    int main() {
      int kase = 0;
      while(cin >> n && n) {
        string s;
        cout << "S-Tree #" << ++kase << ":
    ";
        for(int i = 0; i < n; i++) { cin >> s; v[i] = s[1] - '1'; }
        int m;
        cin >> leaves >> m;
        while(m--) {
          string q;
          cin >> q;
          cout << solve(q);
        }
        cout << "
    
    ";
      }
      return 0;
    }

    我的解答:

    #include<cstdio>
    #include<cstring>
    #include<iostream>
    #include<string>
    #include<algorithm>
    using namespace std;
    //0 left, 1 right
    
    const int N=10;
    char leaves[1<<N];
    //顺序映射表
    int order[N];
    int n;
    
    void solve(char* buf)
    {
            //最终叶节点的编号(从1开始)
            int j=1;
            for(int i=0;i<n;i++)
            {
                    if(buf[order[i]]=='0')
                            j*=2;
                    else
                            j=j*2+1;
            }
            printf("%c", leaves[j-(1<<n)]);
    }
    
    void getorder(char* s)
    {
            for(int i=0;i<n;i++)
            {
                    order[i]=s[1+3*i]-'1';
            }
    }
    
    int main()
    {
            //freopen("./uva712.in", "r", stdin);
            char buf[N*3+1];
            int cnt=0;
            while(scanf("%d", &n)==1 && n)
            {
                    printf("S-Tree #%d:
    ", ++cnt);
                    gets(buf);//read line
    
                    gets(buf);//x1 x2 ...
                    getorder(buf);
    
                    gets(leaves);
                    int m;
                    scanf("%d", &m); gets(buf);//read line
                    for(int i=0;i<m;i++)
                    {
                            gets(buf);
                            solve(buf);
                    }
                    printf("
    
    ");
            }
    
    
        return 0;
    }
  • 相关阅读:
    SPComm的一点小诀窍 spcomm的问题导致数据丢失 0x11与0x13错误
    关于DELPHI数组,指针,字符串转换的例子!(转)
    SQL常用语法大全
    SQL触发器实例讲解
    Delphi 变体类型(Variant)的介绍(流与变体类型的相互转换、变体类型常用的函数)
    delphi 生成条形码(fastreport 实现)
    delphi 判断字符串有中文
    delphi const
    delphi as
    delphi 字符串常识
  • 原文地址:https://www.cnblogs.com/cute/p/3639970.html
Copyright © 2020-2023  润新知