当前位置: 代码迷 >> 综合 >> 习题6-2 S-Trees(树)
  详细解决方案

习题6-2 S-Trees(树)

热度:86   发布时间:2024-01-16 13:53:29.0

题意:

看白书

要点:

题目很简单,就是树的水题,我是直接建树然后模拟,第一次WA主要是最后想输出字符串但没有在末尾加上\0,编译器可以通过但会WA,下次要注意了。这题也可以不建树直接用下标法做,我看了一下网上的代码,确实简单多了


1.建树+模拟

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
int tree[10000],rule[10];
char leaf[10000],out[10];
int n;void search()
{int num,i,j,k;char s[10];scanf("%d", &num);for (i = 0; i < num; i++){scanf("%s", s);for (j = 0; j < strlen(s); j++){int x = rule[j+1];for (k = pow(2, x-1); k <= pow(2, x) - 1; k++)tree[k] = s[j] - 48;}int ans=1;for (j = 1; j <= n; j++){if (tree[ans] == 0)ans = 2 * ans;else if (tree[ans] == 1)ans = 2 * ans + 1;}ans = ans - pow(2, n);out[i] = leaf[ans];}out[num] = '\0';//这里非常重要,第一次WA在这里
}int main()
{int count = 1;while (~scanf("%d", &n), n){memset(tree, 0, sizeof(tree));memset(rule, 0, sizeof(rule));int i,j;char layer[10];for (i = 1; i <= n; i++){scanf("%s", layer);rule[layer[1] - 48] = i;//用rule存储真正的x的顺序}scanf("%s", leaf);search();printf("S-Tree #%d:\n", count++);printf("%s\n", out);printf("\n");}return 0;
}


2.下标法

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define maxn 15000int main()
{int n,i,j,t=1;while (~scanf("%d", &n), n){char leaf[maxn], xn[5], out[maxn];int layer[maxn];for (i = 1; i <= n; i++){scanf("%s", xn);layer[i] = xn[1] - '0';}int num;char temp[maxn];scanf("%s%d", leaf, &num);for (i = 0; i < num; i++){scanf("%s", temp);int k = 0;    //这里开始为0后面直接就等于leaf对应下标for (j = 1; j <= n; j++){k = temp[layer[j]-1] == '1' ? (k << 1) + 1 : k << 1;//下标都是对应的,直接找就可以}out[i] = leaf[k];}out[num] = '\0';printf("S-Tree #%d:\n%s\n\n", t++, out);}return 0;
}