传送门:HDU 3791
题解
对串所构造的二叉树查询, 如果形状不对输出NO
查找到无法匹配的空结点或者当前节点不匹配但未被访问时, 形状不对
注意这里节点关键字是0~9, 所以构造函数里不能是0
AC code:
/*
* Author : adrui
* Language : C++
* Result : Accepted
* Love : yy
* Favorite : Dragon Balls
* Standing in the Hall of Fame
*/
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
#include<iostream>
using namespace std;
#define debug 0
#define LL long long
#define inf 0x7f7f7f7f
#define mod 10003
#define mid ((l + r) >> 1)
#define ls rt << 1, l, mid
#define rs rt << 1|1, mid + 1, r
#define M(a, b) memset(a, b, sizeof(a))
const int maxn = 1000 + 5;
int vis[10];
struct BSTree {
BSTree *lch, *rch;
int key;
BSTree(int key = -1) {
this->key = key;
lch = rch = NULL;
}
void build(char *s) {
int len = strlen(s);
BSTree *rt = this;
for (int i = 0; i < len; ++i) {
int c = s[i] - '0';
BSTree *rt = this;
while (~rt->key) {
if (c < rt->key) {
if (rt->lch == NULL)
rt->lch = new BSTree;
rt = rt->lch;
}
else {
if (rt->rch == NULL)
rt->rch = new BSTree;
rt = rt->rch;
}
}
rt->key = c;
}
}
void query(char *s, int &flag) {
int len = strlen(s);
BSTree *rt = this;
M(vis, 0);
for (int i = 0; i < len; ++i) {
int c = s[i] - '0';
BSTree *rt = this;
while (rt->key != c) {
if (!vis[rt->key]) {
flag = 0; return;
}
if (c < rt->key) {
if (rt->lch == NULL)
{
flag = 0; return;
}
rt = rt->lch;
}
else {
if (rt->rch == NULL)
{
flag = 0; return;
}
rt = rt->rch;
}
}
vis[c] = 1;
}
}
};
int main() {
#if debug
freopen("in.txt", "r", stdin);
#endif //debug
cin.tie(0);
cin.sync_with_stdio(false);
char s[12];
int n;
while (cin >> n, n) {
BSTree rt;
cin >> s;
rt.build(s);
for (int i = 0; i < n; ++i) {
cin >> s;
int flag = 1;
rt.query(s, flag);
if (flag) cout << "YES";
else cout << "NO";
cout << endl;
}
}
return 0;
}