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;
}
posted @ 2011-08-30 11:55  moonbay  阅读(182)  评论(0编辑  收藏  举报