1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
| #include<stdio.h> #include<stdlib.h> #include<string.h> #include<time.h>
#define bool int #define true 1 #define flase 0 #define MAXN 20510 #define N 2010
char str[MAXN]; char word[N]; char string[MAXN]; int len[MAXN]; int n,m; int ans[MAXN],cnt=0,length; int ne[MAXN];
void init() { memset(ans, 0, sizeof ans); cnt = 0; }
void read() { scanf("%[^\n]", str + 1); n = strlen(str + 1); m = 1; while(str[m] != ' ') { word[m] = str[m]; m ++; } -- m;
m = strlen(word + 1);
printf("The definition word: %s\n", word + 1); puts("=============================================\n"); }
void print(){ printf("\nThere are %d words in the article which is same with the definition word %s.\n",cnt,word); if(cnt != 0) { printf("\nThe positions are:\n"); for(int i = 1;i <= cnt; ++ i) { printf("%d ", ans[i]); if(i == cnt) { printf("\n"); } } } puts(""); puts("=============================================\n"); }
void NAIVE_STRING_MACHINE(){ for(int i = m + 1; i <= n; ++ i) { bool flag = true; for(int j = 1, k = i; k <= n && j <= m ; ++ j, ++ k) { if(str[k] != word[j]) { flag = false; break ; } } if(flag) { ans[++ cnt] = i - m - 1; } } }
void next(){ memset(ne, 0, sizeof ne); int i, j; for(i = 2, j = 0;i <= m; i ++) { while(j && word[i] != word[j+1]) { j = ne[j]; } if(word[i] == word[j+1]) { j ++; }
ne[i] = j; } }
void next_fast(){ memset(ne, 0, sizeof ne); int i, j, k; for(i = 2, j = 0 ; i <= m ; i++) { if(word[i] == word[j]) { ne[i] = ne[j]; } else { ne[i] = j; } while(j > 0 && word[i] != word[j]) { j = ne[j-1]; } if(word[i] == word[j]) { j ++; } } }
void KMP() { int i , j;
for(i = m + 1, j = 0;i <= n;i ++) { while(j && str[i] != word[j+1]) { j = ne[j]; } if(str[i] == word[j+1]) j++; if(j == m) { ans[++ cnt] = i - j + 1 - m - 1; } } }
void work1() { init(); printf("Below is the NAIVE_STRING_MATCHING Algorithm...\n\n"); NAIVE_STRING_MACHINE();
print(); }
void work2() { init(); printf("Below is the KNUTH_MORRIS_PRATT Algorithm...\n\n"); next(); KMP();
print(); }
void work3(){ init(); printf("Below is the KNUTH_MORRIS_PRATT Algorithm with faster next[] caculating...\n\n");
next_fast(); KMP();
print(); }
int main(){
freopen("in.in", "r", stdin); freopen("out.out", "w", stdout);
read(); work1(); work2(); work3(); return 0; }
|