POJ-2503 babelfish hash table

Source: Internet
Author: User

The hash table is easy to use because map is faster and easier.

Multiply each character string by the corresponding position and then perform the hash operation.

This problem also encountered a problem. During string copying, because of the direct sizeof (in) because the in function overwrites the global in, in is a pointer variable, so it is not 15 but 4. Each time it is assigned only four bytes, it must be wrong.

The Code is as follows:

#include <cstring>#include <cstdio>#include <cstdlib>#define MOD 2000003using 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;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.