• 字符串哈希初步 洛谷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('
    ');
    }
    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);
    }
  • 相关阅读:
    jquery json 格式教程
    不修改代码就能优化ASP.NET网站性能的一些方法
    C#操作sqlite数据库使用SQLiteParameter传递参数
    60个开发者不容错过的免费资源库
    Java 与 .NET 的平台发展之争
    “一次编写,随处运行” Intel HTML5技术研讨会
    Struts2 高危漏洞修复方案 (S2-016/S2-017)
    AspNetPager 控件使用
    jQueryUI常用功能实战
    验证码生成类
  • 原文地址:https://www.cnblogs.com/ZeonfaiHo/p/6402831.html
Copyright © 2020-2023  润新知