字符串哈希初步 洛谷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);
}

转载于:https://www.cnblogs.com/ZeonfaiHo/p/6402831.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值