poj1204 Word Puzzles

Word Puzzles

题目背景:

poj1204

分析:AC自动机的题,先将所有的匹配串建成AC自动机,然后八个方向用地图来跑即可。详细见代码。

Source:

#include
     
     
      
      
#include
      
      
       
       
#include
       
       
        
        
#include
        
        
         
         
#include
         
         
           #include 
          
            using namespace std; const int dx[9]= {0, -1, -1, 0, 1, 1, 1, 0, -1}; const int dy[9]= {0, 0, 1, 1, 1, 0, -1, -1, -1}; char ss[10000], s[1010][1010]; int f[1100000][27], first[1100000], next[1100000]; int fail[1100000], lent[1100000], queue[1100000]; int tot, cnt, head, tail, n, len, m, q; struct data { int x; int y; char dir; } out[1010]; void build(int v, int x) { if (x == len) { tot++; first[v] = tot; lent[v] = len; return ; } if (!f[v][ss[x] - 'A']) { cnt++; f[v][ss[x] - 'A'] = cnt; } build(f[v][ss[x] - 'A'], x + 1); } void pre_AC(void) { head = 0, tail = 1, queue[tail] = 0; while (head < tail) { head++; for (int i = 0; i < 26; ++i) { if (f[queue[head]][i]) { if(queue[head]) fail[f[queue[head]][i]] = f[fail[queue[head]]][i]; tail++; queue[tail] = f[queue[head]][i]; } else f[queue[head]][i] = f[fail[queue[head]]][i]; } } } void read(void) { cin >> n, cin >> m, cin >> q; for (int i = 0; i < n; ++i) cin >> s[i]; for (int i = 1; i <= q; ++i) { cin >> ss; len = strlen(ss), build(0, 0); } } void find(int l, int r, int head, int type) { if (first[head] && out[first[head]].x < 0) { int v = first[head]; out[v].x = l - lent[head] * dx[type]; out[v].y = r - lent[head] * dy[type]; out[v].dir = type + 'A' - 1; } if (!(l >= 0 && l < n && r >= 0 && r < m)) return ; while (!f[head][s[l][r] - 'A'] && head) head = fail[head]; find(l + dx[type], r + dy[type], f[head][s[l][r] - 'A'], type); } void get(void) { for (int k = 1; k <= 8; ++k) { for(int i = 0; i < n; ++i) find(i, 0, 0, k), find(i, m - 1, 0, k); for(int i = 0; i < m; ++i) find(0, i, 0, k), find(n - 1, i, 0, k); } for (int i = 1; i <= q; ++i) cout << out[i].x << " " << out[i].y << " " << out[i].dir << '\n'; } int main(void) { ios::sync_with_stdio(false); cin.tie(NULL), cout.tie(NULL); memset(out, -1, sizeof(out)); read(); pre_AC(); get(); return 0; } 
           
         
        
        
       
       
      
      
     
     

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值