奥赛一本通 1471 Phone List

1471 Phone List

题目大意

给定若干字符串,判断是否存在一个字符串是另一个的前缀。

知识要点

字典树

解题思路

在字典树中插入一个字符串的同时,如果没有新建节点,那么它是另一个字符串的前缀;如果经过了某个字符串的末尾,那么该字符串是它的前缀。

参考代码

#include <bits/stdc++.h>
using namespace std;

const int N = 100005;
char s[11];
int cnt, trie[N][10], num[N];
bool insert(char* s) {
    int p = 0, flag1 = 1, flag2 = 0;
    for(int i = 0; s[i]; s++) {
        int c = s[i] - '0';
        if(!trie[p][c]) flag1 = 0, trie[p][c] = ++cnt; //新建节点 
        p = trie[p][c];
        if(num[p]) flag2 = 1; //经过字符串末尾 
    }
    num[p] = 1;
    return flag1 || flag2;
}

int main() {
    int t, n, ans;
    scanf("%d", &t);

    while(t--) {
        cnt = ans = 0;
        memset(trie, 0, sizeof(trie));
        memset(num, 0, sizeof(num));
        
        scanf("%d", &n);
        while(n--) {
            scanf("%s", s);
            ans |= insert(s);
        }
        puts(ans ? "NO" : "YES");
    }
    return 0;
}
posted @ 2026-11-03 16:27  萧西待水  阅读(9)  评论(0)    收藏  举报