hdu 1035 Immediate Decodability(字典树)

582 篇文章 0 订阅

题目链接:hdu 1035 Immediate Decodability

题目大意:给定若干01字符串,判断是否有某个字符串为另外一个字符串的前缀。

解题思路:根据出入的字符串建立字典树,然后逐个查找,在查找的过程中如果碰到单词节点,即是存在前缀串。

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int maxn = 1e5+5;
const int maxm = 15;
const int sigma_size = 2;

struct Tire {
    int sz;
    int g[maxn][sigma_size];
    int val[maxn];

    void init();
    int idx(char ch);
    void insert(char* s);
    int find(char* s);
}S;

int N;
char s[maxn][maxm], op[maxm];

bool input () {
    N = 0;
    S.init();

    while (scanf("%s", op) == 1 && strcmp(op, "9")) {
        S.insert(op);
        strcpy(s[N++], op);
    }
    return N;
}

bool judge() {
    for (int i = 0; i < N; i++) {
        if (S.find(s[i]))
            return false;
    }
    return true;
}

int main () {
    int cas = 1;
    while (input()) {
        printf("Set %d is %s\n", cas++, judge() ? "immediately decodable" : "not immediately decodable");
    }
    return 0;
}

void Tire::init() {
    sz = 1;
    val[0] = 0;
    memset(g[0], 0, sizeof(g[0]));
}

int Tire::idx (char ch) {
    return ch - '0';
}

int Tire::find(char* s) {
    int u = 0, n = strlen(s);

    for (int i = 0; i < n; i++) {
        int v = idx(s[i]);

        if (val[u])
            return 1;
        u = g[u][v];
    }
    return val[u] - 1;
}

void Tire::insert(char* s) {
    int u = 0, n = strlen(s);

    for (int i = 0; i < n; i++) {
        int v = idx(s[i]);

        if (g[u][v] == 0) {
            val[sz] = 0;
            memset(g[sz], 0, sizeof(g[sz]));
            g[u][v] = sz++;
        }

        u = g[u][v];
    }
    val[u] = 1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值