Crazy Search poj 1200 哈希

Many people like to solve hard puzzles some of which may lead them to madness. One such puzzle could be finding a hidden prime number in a given text. Such number could be the number of different substrings of a given size that exist in the text. As you soon will discover, you really need the help of a computer and a good algorithm to solve such a puzzle. 
Your task is to write a program that given the size, N, of the substring, the number of different characters that may occur in the text, NC, and the text itself, determines the number of different substrings of size N that appear in the text. 

As an example, consider N=3, NC=4 and the text "daababac". The different substrings of size 3 that can be found in this text are: "daa"; "aab"; "aba"; "bab"; "bac". Therefore, the answer should be 5. 

Input

The first line of input consists of two numbers, N and NC, separated by exactly one space. This is followed by the text where the search takes place. You may assume that the maximum number of substrings formed by the possible set of characters does not exceed 16 Millions.

Output

The program should output just an integer corresponding to the number of different substrings of size N found in the given text.

Sample Input

3 4
daababac

Sample Output

5

Hint

Huge input,scanf is recommended.

就是求长度为n的不同的子串个数。

刚学的哈希,就赶紧做题巩固,结果这么简单的一题写了一个多小时,真的是mmp。。。

还有就是读题一定要认真,真的是,没看到要用sacnf输入。。又是一句mmp。。。

 

/*
@Author: Top_Spirit
@Language: C++
*/
//#include 
#include 
#include 
#include 
using namespace std ;
typedef long long ll ;
const int Maxn = 16e6 +10 ;
const int P = 131 ;
const int MOD = 9991 ;

char s[Maxn] ;
int n, nc ;
//vector < string > ve[Maxn] ;
int Hash[Maxn] ;
int id[500] ;
int _Hash1 ;

//bool Query(){
//    for (int i = 0; i < ve[_Hash].size(); i++){
//        if (strcmp(ve[_Hash][i], s)) return true ;
//    }
//    return false ;
//}

//bool Add (){
//    if (Query()) return true ;
//    ve[_Hash].push_back(s) ;
//}

int main (){
//    cin >> n >> nc >> s ;
    scanf("%d%d%s", &n, &nc, s) ;
//    int len = s.size() ;
    int len = strlen(s) ;
    int ans = 0 ;
    int cnt = 0 ;
    memset(id, -1, sizeof(id)) ;
    memset(Hash, false, sizeof(Hash)) ;
    for (int i = 0; i < len && cnt < nc; i++){
        if (id[s[i]] != -1) continue ;
        id[s[i]] = cnt++ ;
    }
    for (int i = 0; i < len - n + 1; i++){
        _Hash1 = 0 ;
        for (int j = i; j < i + n; j++){
            _Hash1 = (_Hash1 * nc + id[s[j]]);
        }
        if (Hash[_Hash1]) continue ;
        else {
            Hash[_Hash1] = true ;
            ans++ ;
        }
    }
    printf("%d\n", ans) ;
    return 0 ;
}

没有比当傻瓜更简单的事了

为一件事疯狂,总有一天可以从中找到答案

 

你可能感兴趣的:(Hash)