奥赛一本通 1474 Immediate Decodability
1474 Immediate Decodability
题目大意
给出一些数字串,判断是否有一个数字串是另一个串的前缀。(同 1471 Phone List)
知识要点
字典树
解题思路
在字典树中插入一个字符串的同时,如果没有新建节点,那么它是另一个字符串的前缀;如果经过了某个字符串的末尾,那么该字符串是它的前缀。
参考代码
#include <bits/stdc++.h>
using namespace std;
const int N = 100;
char s[11];
int cnt, trie[N][2], 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 = 1, ans = 0;
while(scanf("%s", s) == 1) {
if(s[0] == '9') {
printf("Set %d is %simmediately decodable\n", t++, ans ? "not " : "");
cnt = ans = 0;
memset(trie, 0, sizeof(trie));
memset(num, 0, sizeof(num));
} else ans |= insert(s);
}
return 0;
}

浙公网安备 33010602011771号