zoukankan      html  css  js  c++  java
  • poj 1200 Crazy Search(hash)

    题目链接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, &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
    ", ans );
        return 0;
    }
  • 相关阅读:
    Valid Palindrome
    Path Sum II
    Reverse Integer
    Palindrome Number
    ZigZag Conversion
    函数调用堆栈 涉及汇编(转)
    关于字符指针和字符数组初始化的问题
    Remove Element(第一种方法参考别人)
    c内存分配(转)
    int *ptr=(int *)(&a+1)问题的探讨
  • 原文地址:https://www.cnblogs.com/tallisHe/p/4065769.html
Copyright © 2011-2022 走看看