HDU 3791

传送门: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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值