POJ 2503 Babelfish

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;
}



發佈了138 篇原創文章 · 獲贊 5 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章