字典树的每个节点都标记是不是某个字符串的结尾字符。
依次插入字符串,有两种错误情况:
1.插入时经过了某个是结尾字符的节点
2.到结尾字符时,对应的节点已经存在了
代码:
//
// main.cpp
// 1056 IMMEDIATE DECODABILITY
//
// Created by Baoli1100 on 15/4/5.
// Copyright (c) 2015年 Baoli1100. All rights reserved.
//
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
struct node{
int n;
int next[2];
bool end;
}G[3000];
int Num=1;
bool Insert(char s[]){
int len=strlen(s);
int cur=0;
for(int i=0;i<len;i++){
int k=s[i]-'0';
if(i==len-1&&G[cur].next[k]) return 0;
if(!G[cur].next[k]){
G[cur].next[k]=Num++;
}
cur=G[cur].next[k];
if(G[cur].end) return 0;
}
G[cur].end=1;
return 1;
}
int main(){
char s[20];
int kase=1;
bool res=0;
while(~scanf("%s",s)){
if(s[0]=='9'){
printf("Set %d is ",kase);
if(res) printf("not ");
printf("immediately decodable\n");
memset(G,0,sizeof(G));
Num=1;
kase++;
res=0;
continue;
}
if(!Insert(s)) res=1;
}
}

854

被折叠的 条评论
为什么被折叠?



