http://poj.org/problem?id=1200
hash入门,用karp-rabin做的
1 #include <stdio.h> 2 #include <string.h> 3 #define N 16000100 4 5 char s[1000100] = "\0", mark[26] = "\0"; 6 char hash2[N] = "\0"; 7 int hash1[26] = {0}; 8 int n, nc; 9 10 int main() 11 { 12 int i, j, sum = 0, ncn = 1, result = 0; 13 scanf("%d%d%*c%s", &n, &nc, s); 14 for(j=1,i=0; s[i]; i++) 15 { 16 if(!mark[s[i]-'a']) 17 { 18 mark[s[i]-'a'] = 1; 19 hash1[s[i]-'a'] = j; 20 j = j + 1; 21 if(j == nc+1) 22 { 23 break; 24 } 25 } 26 } 27 sum += hash1[s[n-1]-'a']; 28 for(i=n-1; i>=1; i--) 29 { 30 ncn = ncn * nc; 31 sum += hash1[s[i-1]-'a']*ncn; 32 } 33 hash2[sum] = 1; 34 result ++; 35 for(i=n; s[i]; i++) 36 { 37 sum -= hash1[s[i-n]-'a']*ncn; 38 sum *= nc; 39 sum += hash1[s[i]-'a']; 40 if(!hash2[sum]) 41 { 42 hash2[sum] = 1; 43 result ++; 44 } 45 } 46 printf("%d\n", result); 47 return 0; 48 }