• POJ2503 Babelfish Hash表


    这题用hash表做有点无病呻吟了,因为用map更快更简单。

    把字符串按每一位乘以相应的位置,再进行hash操作。

    这题还做的时候还遇到一个问题,在进行字符串复制的时候,由于直接sizeof(in)由于in在这个函数里面覆盖了全局的in所以in是一个指针变量,所以并不是15而是4,每次只赋值4个字节,肯定是错了点。

    代码如下:

    #include <cstring>
    #include <cstdio>
    #include <cstdlib>
    #define MOD 2000003
    using namespace std;
    
    char s[50], in[15], out[15];
    
    int head[2000003], idx;
    
    struct Node
    {
        char w[15], t[15];
        int next;
    }e[1000005];
    
    void Hash(char *in, char *out)
    {
        int key = 0;
        int length = strlen(in);
        for (int i = 0; i < length; ++i) {
            key += in[i] * (i+1);
        }
        key %= MOD;
        ++idx;
        strcpy(e[idx].w, in);
        strcpy(e[idx].t, out);
        e[idx].next = head[key];
        head[key] = idx;
    }
    
    int find(char *in)
    {
        int length = strlen(in), key = 0;
        for (int i = 0; i < length; ++i) {
            key += in[i] * (i+1);
        }
        key %= MOD;
        for (int i = head[key]; i != -1; i = e[i].next) {
            if (!strcmp(in, e[i].w)) {
                return i;
            }
        } 
        return -1;
    }
    
    int main()
    {
        int ans;
        memset(head, 0xff, sizeof (head));
        idx = -1;
        while (gets(s)) {
            int length = strlen(s);
            if (length != 0) {
                sscanf(s, "%s %s", out, in);
                Hash(in, out);
            }
            else {
                while (gets(s)) {
                    ans = find(s);
                    if (ans == -1) {
                        puts("eh");
                    }    
                    else {
                        printf("%s\n", e[ans].t);
                    }
                }
            }
        }
        return 0;
    }
  • 相关阅读:
    钉钉小程序解析html的方法
    git使用
    electron-vue项目
    数组方法大全
    关于AJAX
    常用的东西
    常用正则表达式
    选项卡
    进度条
    泛型单列
  • 原文地址:https://www.cnblogs.com/Lyush/p/2587852.html
Copyright © 2020-2023  润新知