POJ 2503 Babelfish

9 篇文章 0 订阅
7 篇文章 0 订阅

map解法

#include<bits/stdc++.h>
using namespace std;
map<string,string>p;
int main()
{
    string a,b;
    while(cin>>a)
    {
        if(getchar()=='\n')
            break;
        cin>>b;
        p[b]=a;
    }
    if(p[a]=="")
        cout<<"eh"<<endl;
    else
        cout<<p[a]<<endl;
    while(cin>>a)
    {
        if(p[a]=="")
            cout<<"eh"<<endl;
        else
            cout<<p[a]<<endl;
    }
    return 0;
}

哈希解法

#include<bits/stdc++.h>
using namespace std;
const int maxn=1000000;
const int maxm=100003;  
const int maxlen=12;
class hash
{
    private:
    struct node{
        char ch[maxlen];
        int ptr;
        node* next;
    };
    node *h[maxm],s[maxn];
    int numptr;
    int Hash(char *key)
    {
        unsigned long h=0,g;
        while(*key)
        {
            h=(h<<4)+*key++;
            g=h&0xf0000000L;
            if(g)h^=g>>24;
            h&=~g;
        }
        return h%maxm;
    }
    public:
    void init()
    {
        int i;
        for(i=0;i<maxm;i++)
            h[i]=NULL;
        numptr=0;
    }
    int ins(char ch[])
    {
        int temp=Hash(ch);
        strcpy(s[numptr].ch,ch);
        s[numptr].next=h[temp];
        s[numptr].ptr=numptr;
        h[temp]=&s[numptr];
        numptr++;
        return numptr-1;
    }
    int question(char ch[])
    {
        int temp=Hash(ch);
        node* ptr=h[temp];
        while(ptr)
        {
            if(strcmp(ptr->ch,ch)==0)
                return ptr->ptr;
            ptr=ptr->next;
        }
        return -1;
    }
};
char ch[200000][12];
hash h;
char ch1[12],ch2[12];
int main()
{
    int temp;
    h.init();
    while(scanf("%s",ch1))
    {
        if(getchar()!=' ')
            break;
        scanf("%s",ch2);
        temp=h.ins(ch2);
        strcpy(ch[temp],ch1);
    }
    do
    {
        temp=h.question(ch1);
        if(temp==-1)
            printf("eh\n");
        else
            printf("%s\n",ch[temp]);
    }while(scanf("%s",ch1)!=EOF);
    return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值