好几天没做题了,都快退化了,早上刚1A了一题。 /* coder: ACboy date: 2010-3-13 result: 1A description: UVa 712 S-Trees */ #include <iostream> #include <map> #include <string> using namespace std; struct Node { struct Node * lchild, * rchild; string name; char value; }; int n; int pos; string name[1028]; Node * newNode(string name) { Node * u = new Node; u->name = name; u->rchild = u->lchild = NULL; u->value = '0'; return u; } // 递归建树,terminal用来存储叶子节点的值。 Node * buildTree(string name[], int cur, string terminal) { if (cur == n) { Node * p = newNode(name[cur]); p->value = terminal[pos++]; return p; } else { Node * u = newNode(name[cur]); u->lchild = buildTree(name, cur + 1, terminal); u->rchild = buildTree(name, cur + 1, terminal); return u; } } // 深度优先遍历到达叶子节点后返回叶子节点的值。 char dfs(Node * root, string value) { Node * u = root; int len = value.size(); for (int i = 0; i < len; i++) { if (value[i] == '0') { u = u->lchild; } else { u = u->rchild; } } return u->value; } int main() { int i; int count = 0; #ifndef ONLINE_JUDGE freopen("712.txt", "r", stdin); #endif while (scanf("%d/n", &n) != EOF) { if (n == 0) break; for (i = 0; i < n; i++) { cin >> name[i]; } string terminal; cin >> terminal; pos = 0; Node * root; root = buildTree(name, 0, terminal); int k; cin >> k; cout << "S-Tree #" << ++count << ":" << endl; for (i = 0; i < k; i++) { string temp; cin >> temp; cout << dfs(root, temp); } cout << endl << endl; } return 0; }