首页 > 其他 > 详细

poj 1200 Crazy Search

时间:2014-10-31 20:28:15      阅读:229      评论:0      收藏:0      [点我收藏+]

题目链接http://poj.org/problem?id=1200

 

分析

从数据来看,该题目使用线性时间算法,可见子串的比较是不可能的;

使用hash可以在常数时间内查找,可以常数时间内判重,可以再线性时间内解决问题;

问题关键在与Hash函数的选择,使得子串之间的Hash值不同;

由于NC的提示,使用NC作为基数,其他字符分配不同的数码,从1-NC,再求取Hash值,保证函数为单一映射;

 

代码

#include <stdio.h>
#include <string.h>

const int N = 1000000;
const int MAX_N = 16000000;
int hash[MAX_N];
char A[N];
int value[128];

int main( )
{
    int N, NC, hashVal, valueKey = 0;
    int len, ans = 0, Count = 0;

    memset( value, 0, sizeof( value ) );
    memset( A, 0, sizeof( A ) );
    memset( hash, 0, sizeof( hash ) );
    scanf( "%d %d\n", &N, &NC );
    scanf( "%s", A );

    len = strlen( A );
    for ( int i = 0; i < len; ++i )
    {
        if ( value[A[i]] == 0 )
            value[A[i]] = ++valueKey;

        if ( valueKey == NC )
            break;
    }

    for ( int i = 0; i + N <= len; ++i )
    {
        hashVal = 0;
        for ( int j = i; j < i + N; ++j )
            hashVal = hashVal * NC + value[A[j]] - 1;
        if ( hash[hashVal] == 0 )
        {
            hash[hashVal] = 1;
            ans++;
        }
    }

    printf( "%d\n", ans );
    return 0;
}

poj 1200 Crazy Search

原文:http://www.cnblogs.com/tallisHe/p/4065769.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!