Wild words
题目背景:
分析:虽然不想说,但是我不得不说,这个题刷新了我对“trie树很亲民”的认知,本题是trie + dfs因为存在通配符,就需要进行模糊匹配的处理,代码就有点繁琐了。具体的解题方向详见代码注释。
Source:
#include
#include
#include
#include
#include
#include
using namespace std; int t, n, tot, m; int cnt[1000000]; int first[1000000], nxt[1000000]; bool able[1000000]; string s; struct TRIE { int son[28]; /*因为有两个通配符的存在,所以注意空间要开大才行*/ int num; } trie[500000]; void build_trie(string &s, int num) { int len = s.size(); int position = 0; for(int i = 0; i < len; ++i) { int pos; if(s[i] == '?') pos = 27; /*如果有?存为27*/ else if(s[i] == '*') pos = 26; /*如果有*存为26*/ else pos = s[i] - 'a'; /*其余照常*/ if(!trie[position].son[pos]) trie[position].son[pos] = ++tot; position = trie[position].son[pos]; } if(!nxt[position]) nxt[position] = num, first[num] = num; else first[num] = nxt[position]; /*这两句运用了并查集的思想,将相同的串放在一起, 其实还可以写成邻接表或stl实现,就由读者自行挖掘了*/ } void find(string &s, int pos, int k, int len) { /*因为涉及到dfs所以需要写成递归传参*/ int i; if(trie[pos].son[26]) { /*存在*号通配符,直接搜索每一位*/ for(i = 0; s[i + k]; ++i) find(s, trie[pos].son[26], k + i, len); find(s, trie[pos].son[26], k + i, len); } if(k == len) { if(nxt[pos]) able[nxt[pos]] = true; /*判断是否为模式串结束点*/ return ; } if(trie[pos].son[27]) find(s, trie[pos].son[27], k + 1, len); /*存在?搜索下一位*/ if(trie[pos].son[s[k] - 'a']) find(s, trie[pos].son[s[k] - 'a'], k + 1, len); } int main() { int i, n, m; cin >> n >> m; string s; for(i = 1; i <= n; ++i) { cin >> s; build_trie(s, i); } for(i = 1; i <= m; ++i) { memset(able, false, sizeof(able)); cin >> s; find(s, 0, 0, s.size()); int i; for(i = 1; i <= n; ++i) if(able[first[i]]) { cout << i - 1; break; } if(i == n + 1) { cout << "Not match" << '\n'; continue; } for(i++; i <= n; ++i) if(able[first[i]]) cout << " " << i - 1; cout << '\n'; } return 0; }