POJ 2503.Babelfish

题目:http://poj.org/problem?id=2503

AC代码(C++):

#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <vector>
#include <queue>
#include <math.h>
#include <string>
#include <string.h>
#include <bitset>

#define INF 0xfffffff
#define MAXN 100005

using namespace std;

const int N = 100005;
const int H = 99997;

struct Node  
{  
    char f[12];
    char e[12];
    int next;
};  
Node node[N];
int cur;
int hashTable[H];

void initHash()  
{  
    cur = 0;  
    for (int i = 0; i < H; ++i) hashTable[i] = -1;  
}

int getHash(char* f){
	int hash = 0;
	for(int i = 0; f[i]!='\0'; i++)hash += (f[i] - 'a') * (int)pow(4.0,i+1) % H;
	return hash%H;
}
  
void insertHash(char* f, char* e)
{
	int h = getHash(f);
    strcpy(node[cur].f,f);
    strcpy(node[cur].e,e);
    node[cur].next = hashTable[h];
    hashTable[h] = cur;
    cur++;
}

bool searchHash(char* f)
{
    int h = getHash(f);
    int next = hashTable[h];
    while (next != -1)
    {
        if (strcmp(node[next].f,f)==0){
        	strcpy(f,node[next].e);
        	return true;
        }
        next = node[next].next;
    }
    return false;
}

int main(){
	char f[12];
	char e[12];
	char tmp;
	initHash();
	while(1){
		if((tmp = getchar())=='\n')break;
		e[0] = tmp;
		int cnt = 1;
		while(1){
			if((tmp = getchar())==' ')break;
			e[cnt++] = tmp;
		}
		e[cnt] = '\0';
		cin>>f;
		getchar();
		
		insertHash(f,e);
	}
	
	while(cin>>f){
		if(searchHash(f))cout<<f<<endl;
		else cout<<"eh\n";
	}
}
总结: 简单的串哈希. 听说用map做的更快.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值