poj1816 Wild words

Wild words

题目背景:

poj1816

分析:虽然不想说,但是我不得不说,这个题刷新了我对“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; } 
            
          
         
         
        
        
       
       
      
      

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值