题目链接:http://poj.org/problem?id=1056
这道题用字典树可接,具体思路就是每遇到一个单词都把它插入到字典树之中,然后如果遇到了9,就查询每个单词的词尾标记的数量,如果词尾标记的数量多于1,则证明另外一个单词是这个单词的前缀,输出失败,否则的话输出成功。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
struct trie{
int ch[110][2];
int val[100];
int sz;
void reset(){
sz = 1; memset(ch[0], 0, sizeof(ch[0]));
memset(val, 0, sizeof(val));
}
int idx(char c){
return c - '0';
}
void insert(string s, int v){
int u = 0, n = s.size();
for (int i = 0; i < n; i++){
int c = idx(s[i]);
if (!ch[u][c]){
memset(ch[sz], 0, sizeof(ch[sz]));
val[sz] = 0;
ch[u][c] = sz++;
}
u = ch[u][c];
}
val[u] = v;
}
bool query(string s, int v){
int u = 0, n = s.size(), cnt = 0;
for (int i = 0; i < n; i++){
int c = idx(s[i]);
u = ch[u][c];
if (val[u] == v) cnt += 1;
}
if (cnt > 1) return 0;
return 1;
}
};
trie t;
string s;
vector<string> v;
int main(){
t.reset();
int p = 1;
while (cin >> s){
if (s.compare("9") == 0){
printf("Set %d is ", p++);
bool f = 1;
for (int i = 0; i < v.size(); i++)
if (!t.query(v[i], -1)){
f = 0; break;
}
if (!f) printf("not ");
printf("immediately decodable\n");
t.reset();
v.clear();
}
else{
v.push_back(s);
t.insert(s, -1);
}
}
return 0;
}
当然,暴力也是可以水过的~