字符串哈希初步 洛谷3370

跑得好慢QAQ

#include<cstdio>
#include<cctype>
#include<cstring>
using namespace std;
inline void read(int &x)
{
    x = 0;
    int flag = 1;
    char c;
    while(! isgraph(c = getchar()))
        if(c == '-')
            c = getchar();
    while(isgraph(c))
        x = x * 10 + c - '0', c = getchar();
    x *= flag;
}
inline void read(char *s)
{
    char c;
    while(! isgraph(c = getchar()));
    int top = 0;
    while(isgraph(c))
        *(s + (top ++)) = c, c = getchar();
}
const int MAXN = 1 << 14;
const int MAXLEN = 1 << 11;
int top;
int head[1 << 20];
int hash(char *s)
{
    int len = strlen(s);
    unsigned int h = 0;
    for(int i = 0; i < len; i ++)
        h = h * 31 + *(s + i);
    return h & 0x7fffffff;
}
struct Table
{
    char s[MAXLEN];
    int next;
}table[MAXN];
void print(int x)
{
    if(x == 0)
        putchar('0');
    int ans[1 << 4], top = 0;
    while(x)
        ans[top ++] = x % 10, x /= 10;
    for(; top; top --)
        putchar(ans[top - 1] + '0');
    putchar('\n');
}
int main()
{
    int n;
    read(n);
    int top = 0;
    memset(head, - 1, sizeof(head));
    int ans = 0;
    char s[MAXLEN];
    memset(s, 0, sizeof(s));
    for(int i = 0; i < n; i ++)
    {
        read(s);
        int len = strlen(s);
//        int ha = hash(s) % (1 << 20);
        int ha = 1;
        int j = head[ha];
        while(1)
        {
            if(j == - 1)
            {
                for(int k = 0; k < len; k ++)
                    table[top].s[k] = s[k];
                table[top].next = head[ha];
                head[ha] = top ++;
                ans ++;
                break;
            }
            else if (len == strlen(table[j].s))
            {
                int flag = 1;
                for(int k = 0; k < len; k ++)
                    if(table[j].s[k] != s[k])
                        flag = 0;
                if(flag)
                    break;
            }
            j = table[j].next;
        }
        for(int i = 0; i < len; i ++)
            s[i] = 0;
    }
    print(ans);
}
posted @ 2017-01-17 10:47  Zeonfai  阅读(140)  评论(0编辑  收藏  举报