Codeforces Round #291 (Div. 2) C. Watto and Mechanism Trie
链接:
http://codeforces.com/contest/514/problem/C
题意:
字符串匹配,要求刚好有一个字符不一样
题解:
字典树,直接暴力dfs就可以了,开始以为会超时,其实并不会
代码:
31 int n, m; 32 int Trie[MAXN][3], v[MAXN]; 33 int sz = 1; 34 string s; 35 36 void insert(string s) { 37 int now = 1; 38 rep(i, 0, s.length()) { 39 int x = s[i] - 'a'; 40 if (!Trie[now][x]) Trie[now][x] = ++sz; 41 now = Trie[now][x]; 42 } 43 v[now] = 1; 44 } 45 46 bool dfs(int now, int len, int fg) { 47 if (len == s.length()) { 48 if (v[now] && fg) return true; 49 return false; 50 } 51 int x = s[len] - 'a'; 52 if (Trie[now][x]) if (dfs(Trie[now][x], len + 1, fg)) return true; 53 if (!fg) { 54 x = (x + 1) % 3; 55 if (Trie[now][x]) if (dfs(Trie[now][x], len + 1, 1)) return true; 56 x = (x + 1) % 3; 57 if (Trie[now][x]) if (dfs(Trie[now][x], len + 1, 1)) return true; 58 } 59 return false; 60 } 61 62 int main() { 63 ios::sync_with_stdio(false), cin.tie(0); 64 cin >> n >> m; 65 while (n--) { 66 cin >> s; 67 insert(s); 68 } 69 while (m--) { 70 cin >> s; 71 if (dfs(1, 0, 0)) cout << "YES" << endl; 72 else cout << "NO" << endl; 73 } 74 return 0; 75 }