//3407
//题意:给一段字符串,由状态转换图画出状态转换表
1 #include "bits/stdc++.h" 2 using namespace std; 3 char str[10010]; 4 struct DfaNode { 5 char ch; 6 int son, next, father, suffix; 7 bool danger; 8 } dfaNode[10010]; 9 int cntDfaNode; 10 11 void BuildTree(char *s, int len, int pos, int index) 12 { 13 if(dfaNode[index].son == 0) { 14 ++cntDfaNode; 15 dfaNode[index].son = cntDfaNode; 16 dfaNode[cntDfaNode].father = index; 17 dfaNode[cntDfaNode].ch = s[pos]; 18 if(pos + 1 == len) 19 dfaNode[cntDfaNode].danger = 1; 20 else 21 BuildTree(s, len, pos + 1, cntDfaNode); 22 } else { 23 for(index = dfaNode[index].son; index && dfaNode[index].ch != s[pos]; index = dfaNode[index].next); 24 if(dfaNode[index].ch == s[pos] && pos + 1 == len) 25 dfaNode[index].danger = 1; 26 else if(dfaNode[index].ch == s[pos]) 27 BuildTree(s, len, pos + 1, index); 28 else { 29 ++cntDfaNode; 30 dfaNode[index].son = cntDfaNode; 31 dfaNode[cntDfaNode].father = index; 32 dfaNode[cntDfaNode].ch = s[pos]; 33 if(pos + 1 == len) 34 dfaNode[cntDfaNode].danger = 1; 35 else 36 BuildTree(s, len, pos + 1, cntDfaNode); 37 } 38 } 39 } 40 41 int q[10010]; 42 void BuildDfa() 43 { 44 int child(int x, char ch); 45 int index, l, r; 46 l = r = 1; 47 q[1] = 1; 48 dfaNode[1].suffix = 1; 49 while(l <= r) { 50 if(dfaNode[l].danger == 0) { 51 for(index = dfaNode[l].son; index; index = dfaNode[index].next) { 52 ++r; 53 q[r] = index; 54 } 55 } 56 ++l; 57 } 58 int i; 59 for(i = 2; i <= r; ++i) { 60 if(dfaNode[q[i]].father == 1) { 61 dfaNode[q[i]].suffix = 1; 62 continue; 63 } 64 dfaNode[q[i]].suffix = child(dfaNode[dfaNode[q[i]].father].suffix, dfaNode[q[i]].ch); 65 if(dfaNode[dfaNode[q[i]].suffix].danger) 66 dfaNode[q[i]].danger = 1; 67 } 68 } 69 70 int res[10010][30]; 71 72 int child(int index, char ch) 73 { 74 int sonIndex; 75 for(sonIndex = dfaNode[index].son; sonIndex && dfaNode[sonIndex].ch != ch; sonIndex = dfaNode[sonIndex].next); 76 if(sonIndex) 77 return sonIndex; 78 else if(index == 1) 79 return 1; 80 else 81 return child(dfaNode[index].suffix, ch); 82 } 83 84 int main() 85 { 86 while(scanf("%s", str), strcmp(str, "0")) { 87 memset(dfaNode, 0, sizeof(dfaNode)); 88 memset(res, 0, sizeof(res)); 89 cntDfaNode = 1; 90 //建树,建dfa 91 BuildTree(str, strlen(str), 0, 1); 92 BuildDfa(); 93 //遍历str 94 int index, sonIndex, i; 95 for(i = 0, index = 1; i <= strlen(str); index = child(index, str[i]), ++i) { 96 char c; 97 for(c = 'a'; c <= 'z'; ++c) { 98 res[index - 1][c - 'a'] = child(index, c) - 1; 99 } 100 } 101 for(i = 0; i <= strlen(str); ++i) { 102 printf("%d", i); 103 for(int j = 0; j < 26; ++j) { 104 printf(" %d", res[i][j]); 105 } 106 puts(""); 107 } 108 } 109 }