CF Watto and Mechanism (字典树+深搜)
Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".
Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you.
The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively.
Next follow n non-empty strings that are uploaded to the memory of the mechanism.
Next follow m non-empty strings that are the queries to the mechanism.
The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'.
For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes).
2 3
aaaaa
acacaca
aabaa
ccacacc
caaac
YES
NO
NO
同样的思路,错了很多次,看来实现能力还是不够强。
字典树加搜索,没什么好说的,注意必须要改变一个字母就行。
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 const int SIZE = 800000; 5 struct Node 6 { 7 Node * next[3]; 8 bool word; 9 }* ROOT = nullptr; 10 char S[SIZE]; 11 12 bool dfs(char *,Node *,bool); 13 int main(void) 14 { 15 int n,m; 16 char ch; 17 ROOT = new Node; 18 for(int i = 0;i < 3;i ++) 19 { 20 ROOT -> next[i] = nullptr; 21 ROOT -> word = false; 22 } 23 24 cin >> n >> m; 25 cin.ignore(); 26 for(int i = 0;i < n;i ++) 27 { 28 Node * cur = ROOT; 29 while(cin.get(ch) && ch >= 'a' && ch <= 'c') 30 { 31 if(cur -> next[ch - 'a']) 32 cur = cur -> next[ch - 'a']; 33 else 34 { 35 cur -> next[ch - 'a'] = new Node; 36 cur = cur -> next[ch - 'a']; 37 for(int i = 0;i < 3;i ++) 38 cur -> next[i] = nullptr; 39 cur -> word = false; 40 } 41 } 42 cur -> word = true; 43 } 44 for(int i = 0;i < m;i ++) 45 { 46 cin >> S; 47 if(dfs(S,ROOT,true)) 48 puts("YES"); 49 else 50 puts("NO"); 51 } 52 53 return 0; 54 } 55 56 bool dfs(char * s,Node * t,bool chance) 57 { 58 if(!t) 59 return false; 60 if(!(*s)) 61 { 62 if(t -> word && !chance) 63 return true; 64 return false; 65 } 66 67 if(dfs(s + 1,t -> next[*s - 'a'],chance)) 68 return true; 69 if(chance) 70 for(int i = 0;i < 3;i ++) 71 if(i != (*s - 'a')) 72 if(dfs(s + 1,t -> next[i],false)) 73 return true; 74 return false; 75 }