poj-2503

#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <iostream>
#include <map>
#include <string>

using namespace std;

struct dict_entry{
    int hval;
    char foreign[15];
    char local[15];
    struct dict_entry * next;
};

const int MAXH = 999999;

typedef struct dict_entry dict_entry;

dict_entry * dict[MAXH];

map<string, string> dictMap;

int hash(char * word) {
    long step = 1;
    long acc = 0;
    while(*word) {
        // acc += (*word) * step;
        // step *= 10;
        acc += (*word) * (*word);
        word++;
    }
    return acc%MAXH;
}

void fillInHash(char * local, char * foreign) {
    // printf("fillInHash %s %s\n", local, foreign);
    int havl = hash(foreign);
    dict_entry * prev = dict[havl];
    dict_entry * new_entrty = (dict_entry *)malloc(sizeof(dict_entry));
    dict[havl] = new_entrty;
    new_entrty->next = prev;
    new_entrty->hval = havl;
    // printf("memcpy foreign %d\n", (int)strlen(foreign));
    memcpy(new_entrty->foreign, foreign, strlen(foreign));
    // printf("memcpy local %d\n", (int)strlen(local));
    memcpy(new_entrty->local, local, strlen(local));
}

const char * translate(char * foreign) {
    int havl = hash(foreign);
    dict_entry * search = dict[havl];
    while (search) {
        if (!strcmp(foreign, search->foreign)) {
            return search->local;
        }
        search = search->next;
    }
    return "eh";
}

int main() {
    dictMap.clear();
    memset(dict, 0, sizeof(dict));
    char line[30] = "";
    char foreign[15] = "";
    char local[15] = "";
    
    while(cin.getline(line, sizeof(line)) && line[0]!='\0')
    {
        sscanf(line,"%s %s", local ,foreign);
        // fillInHash(local , foreign);
        dictMap[string(foreign)] = string(local);
    }

    char translated[15] = "";
    while(cin.getline(translated, sizeof(line)) && translated[0]!='\0')
    {
        map<string, string>::iterator it;
        it = dictMap.find(string(translated));
        if (it == dictMap.end()) {
            printf("eh\n");
        } else {
            printf("%s\n", dictMap[string(translated)].c_str());
        }
    }

}


水题, 不过因为在malloc之后忘了memset 0, 结果 WA了好几次.... (因为这次的hash 成员有字符串数组,并且不保证被全员覆盖,比如 申请的是15长度,只memcpy一个长度为10的字符串,那么第十一个字符不能保证是结束符,因此需要全部初始为0),这其实是常识了......

又比较一下自己搞的hash与直接用STL的性能区别, 拉链法:

C++

 454MS(hash函数用的是ELFhash,一个比较NB的字符串hash法)

 547MS(hash函数用的是自己写的简单hash,每个字母的平方和)

 875MS (STL MAP, 虽然慢,但是空间占的没那么大)

还值得一提的就是本题的输入以空格结束的判定, 方法算是比较取巧吧, sscanf以前用的机会少.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值