UVA10282- Babelfish

题意:到了一个国家,这个国家的每个单词的意思跟英语单词的意思一一对应,让你输入英语单词查找是否有所要找的单词

思路:利用哈系函数,或是STL中的map

#include<iostream>   
#include<cstdio>   
#include<cstring>   
#define MAXN 100003 
using namespace std;   
typedef char Word[12]; 


Word english[MAXN], foreign[MAXN]; 
const int HashSize = 100003; 
int N, head[HashSize], next[HashSize]; 

void init_lookup_table() { 
    memset(head, 0, sizeof(head)); 
} 

int hash(char *str) { // 字符串哈希函数 
    int hash = 0; 
    while (*str) 
        hash = hash * 10 + (*str++); 
    return 
        (hash & 0x7FFFFFFF) % HashSize; 
} 

int add_hash(int s) { 
    int h = hash(foreign[s]); 
    next[s] = head[h]; 
    head[h] = s; 
    return 1; 
} 

int search(char *s) { 
    int h = hash(s); 
    int u = head[h]; 
    while (u){ 
        if(strcmp(foreign[u], s) == 0) 
            return u; 
        u = next[u]; 
    } 
    return -1; 
} 

int main(){ 
    char str[25]; 
    N = 1; 
    init_lookup_table(); 
    while (gets(str)){ 
        if(str[0]=='\0') 
            break; 
        int i;  
        for(i = 0; str[i] != ' '; ++i) 
            english[N][i] = str[i]; 
        english[N][i] = '\0'; 
        char *p = str + i + 1;  
        i = 0;  
        while (*p) 
            foreign[N][i++] = *p++; 
        foreign[N][i] = '\0'; 
        add_hash(N); 
        ++N; 
    } 
    // 查询 
    while (gets(str)) { 
        int index = search(str); 
        if (index == -1) 
            puts("eh"); 
        else 
            printf("%s\n", english[index]); 
    } 
    return 0; 
} 

STL

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<string>
#include<map>
using namespace std;

char str[100];
char a[30], b[30], c[30];

int main () {
    map<string, string> s;
    while (gets(str) != NULL) {
        if (str[0] == '\0')
            break; 
        sscanf(str, "%s%s", a, b); 
        s[b] = a;
    }
    while (gets(c)) {
        if (s.find(c) == s.end()) 
            printf("eh\n"); 
        else 
            cout << s[c] << endl;
    }    
    return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值