zoukankan      html  css  js  c++  java
  • hdu 3407 DFA

    上次在北大暑期课期末考试里遇到这道题。最开始我是用BF实现DFA,超时。后来参考别人的程序用Trie实现,过了,但是还是理解得不够透彻。这几天做了不少KMP的题目,今天就用KMP实现了这个DFA,过了,很有成就感,呵呵~~

    /*
    * hdu3407/linux.cpp
    * Created on: 2011-7-29
    * Author : ben
    */
    #include
    <cstdio>
    #include
    <cstdlib>
    #include
    <cstring>
    #include
    <cmath>
    #include
    <algorithm>
    using namespace std;

    #define MAX_LEN 10005
    char pattern[MAX_LEN];
    int state[MAX_LEN][26];
    int len;
    int nextval[MAX_LEN];

    void get_next() {
    int i = 0, j = -1;
    int parlen = len;
    nextval[
    0] = -1;
    while (i <= parlen) {
    if (j == -1 || pattern[i] == pattern[j]) {
    i
    ++;
    j
    ++;
    nextval[i]
    = j;
    }
    else {
    j
    = nextval[j];
    }
    }
    }

    void work() {
    int i, j, cur;
    char c;
    while (scanf("%s", pattern) != EOF) {
    if (strcmp(pattern, "0") == 0) {
    break;
    }
    len
    = strlen(pattern);
    get_next();
    memset(state,
    0, sizeof(state));
    for (cur = 0; cur <= len; cur++) {
    for (c = 'a'; c <= 'z'; c++) {
    i
    = cur;
    while(i >= 0 && c != pattern[i]) {
    i
    = nextval[i];
    }
    state[cur][c
    - 'a'] = i + 1;
    }
    }
    for (i = 0; i <= len; i++) {
    printf(
    "%d", i);
    for (j = 0; j < 26; j++) {
    printf(
    " %d", state[i][j]);
    }
    printf(
    "\n");
    }
    }
    }

    int main() {
    #ifndef ONLINE_JUDGE
    freopen(
    "data.in", "r", stdin);
    #endif
    work();
    return 0;
    }
  • 相关阅读:
    052-240(新增70题2018)
    052-239(新增70题2018)
    052-238(新增70题2018)
    052-237(新增70题2018)
    052-236(新增70题2018)
    052-235(新增70题2018)
    Elasticsearch和Solr的区别
    单点登录流程图
    创建购物车需要考虑哪些因素?以及解决方案
    消息队列在项目中的应用
  • 原文地址:https://www.cnblogs.com/moonbay/p/2159425.html
Copyright © 2011-2022 走看看