# bzoj 1819: 电子字典 Trie

Description

Input

Output

## 题解:

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
x=0;char ch;bool flag = false;
while(ch=getchar(),ch<'!');if(ch == '-') ch = getchar(),flag = true;
while(x=10*x+ch-'0',ch=getchar(),ch>'!');if(flag) x=-x;
}
const int maxn = 210010;
int ch[maxn][26],nodecnt;
bool ed[maxn];
inline void insert(char *s){
int nw = 0;
for(int i=0,c;s[i];++i){
c = s[i] - 'a';
if(ch[nw][c] == 0) ch[nw][c] = ++ nodecnt;
nw = ch[nw][c];
}ed[nw] = true;
}
int vis[maxn],T,len,ans;
bool flag;
char s[maxn];
inline void dfs(int u,int i,int us){
if(i == len && us == 1 && ed[u]){flag = 1;return ;}
if(i == len && us == 0 && ed[u]){
if(vis[u] != T) ++ ans,vis[u] = T;
return;
}
if(i < len && us == 1) dfs(u,i+1,us-1);
if(us == 1){
for(int c=0;c<26;++c){
if(ch[u][c]){
dfs(ch[u][c],i,0);
if(c != (s[i+1]-'a')) dfs(ch[u][c],i+1,0);
}
}
}
if(i == len) return;
if(ch[u][s[i+1]-'a']) dfs(ch[u][s[i+1]-'a'],i+1,us);
}
int main(){
for(int i=1;i<=n;++i){
scanf("%s",s);
insert(s);
}
for(T=1;T<=m;++T){
scanf("%s",s+1);len = strlen(s+1);
flag = 0;ans = 0;
dfs(0,0,1);
if(flag) puts("-1");
else printf("%d\n",ans);
}
getchar();getchar();
return 0;
}


(乃们不要问我为什么dfs和qingdaobaibai的那么像)

posted @ 2017-03-13 07:07  Sky_miner  阅读(153)  评论(0编辑  收藏  举报