POJ 1200 Hash

POJ 1200
题目链接:
http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=17714
题意:
问长度为n的连续子串在一个给定串种有几种。
思路:
用Rabin-Karp的方法设计一下Hash值即可。由于数据范围小所以不需要模。
源码:

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
using namespace std;
const int MAXN = 16000000 + 1;
int use[MAXN];
int mark[1000];
char str[MAXN];
int main()
{
    int n, nc;
    while(scanf("%d%d%s", &n, &nc, str) != EOF){
        memset(use, 0, sizeof(use));
        memset(mark, 0, sizeof(mark));
        int len = strlen(str);
        int cnt = 0;
        for(int i = 0 ; i < len ; i++)
            if(mark[str[i]] == 0)    mark[str[i]] = ++cnt;
        int sum = 0;
        int ans = 0;
        int xi = 1;
        for(int i = 0 ; i < len ; i++){
//            printf("i = %d, sum = %d\n", i, sum);
//            printf("ans = %d\n", ans);
            if(i < n - 1)
                sum = sum * nc + mark[str[i]] - 1, xi *= nc;
            else if(i == n - 1){
                use[sum] = 1;
                ans++;
                sum = sum * nc + mark[str[i]] - 1;
            }
            else{
//                printf("sum = %d, mark[%c] = %d, xi = %d, nc = %d\n", sum, str[i - n], mark[str[i - n]], xi, nc);
                sum = (sum - (mark[str[i - n]] - 1) * xi) * nc + mark[str[i]] - 1;
                if(use[sum] == 0)   use[sum] = 1, ans++;
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}

你可能感兴趣的:(POJ 1200 Hash)