poj 2503 Babelfish

// 题意: 给出一组字符串对(s1,s2),和待查询的单词s2,输出单词s2的对应字符串s1,如果找不到则输出‘eh’
#include <iostream> // trie树
#include <string>
using namespace std ;
#define maxn 100100
struct Node
{
int next[26];
int pos; //记录该节点所代表的字符串出现的位置,若pos=-1则说明从未出现过
}table[1000100]; //maxn*10,因为每个单词至多10个字母
int cur;
void init()
{
memset(table[0].next,-1,sizeof(table[0].next));
cur=1;
}
void insert(char ch[],int pos)
{
Node* p=&table[0]; //table[0]作为根节点
for(int i=0;ch[i];++i)
{
int j=ch[i]-'a';
if(p->next[j]==-1)
{
p->next[j]=cur++;
Node* q=&table[p->next[j]];
for(int k=0;k<26;++k)
q->next[k]=-1;
q->pos=-1;
}
p=&table[p->next[j]];
}
p->pos=pos;
}
int find(char ch[])
{
Node* p=&table[0];
for(int i=0;ch[i];++i)
{
int j=ch[i]-'a';
if(p->next[j]==-1)
return -1;
else
p=&table[p->next[j]];
}
return p->pos;
}
char s1[maxn][12],s2[maxn][12];
int main()
{
init();
char s[30];
int rear=0;
while(gets(s))
{
if(strlen(s)==0) //遇到空行
break;
sscanf(s,"%s %s",s1[rear],s2[rear]);
insert(s2[rear],rear);
rear++;
}
while(~scanf("%s",s))
{
int i=find(s);
if(i==-1)
printf("eh\n");
else
printf("%s\n",s1[i]);
}
return 0 ;
}


// 题意: 给出一组字符串对(s1,s2),和待查询的单词s2,输出单词s2的对应字符串s1,如果找不到则输出‘eh’
#include <iostream> // 字符串哈希
#include <string>
using namespace std;
#define M 1000000
//M如果较小则不能很好地避免冲突,解决冲突需要更多的时间,会TLE,比如200000 当然不能过大,会MLE,比如10000000
//M取适合的值,既可以避免Hash开得太大,同时又可以减少冲突
char Hash[M][12],res[M][12];
int ELFHash(char ch[])
{
int h = 0;
int x = 0;
for(int i=0;ch[i];++i)
{
h = (h << 4) + (ch[i]);
if ((x = h & 0xF0000000L) != 0)
{
h ^= (x >> 24);
h &= ~x;
}
}
return h % M;
}

int main()
{
char s[30],s1[12],s2[12];
int ind;
while(gets(s))
{
if(strlen(s)==0) //遇到空行
break;
sscanf(s,"%s %s",s1,s2);
ind=ELFHash(s2);
while(strcmp(Hash[ind],"")!=0)
ind=(ind+1)%M;
strcpy(Hash[ind],s2);
strcpy(res[ind],s1);
}
while(~scanf("%s",s))
{
ind=ELFHash(s);
if(strcmp(Hash[ind],"")==0)
printf("eh\n");
else
{
while(strcmp(Hash[ind],s)!=0)
ind=(ind+1)%M;
printf("%s\n",res[ind]);
}
}
return 0;
}



// 题意: 给出一组字符串对(s1,s2),和待查询的单词s2,输出单词s2的对应字符串s1,如果找不到则输出‘eh’
#include <iostream> // map
#include <map>
#include <string>
using namespace std;
int main()
{
map<string,string> col;
char s[30],s1[12],s2[12];
while(gets(s))
{
if(strlen(s)==0) //遇到空行
break;
sscanf(s,"%s %s",s1,s2);
col[s2]=s1;
}
while(~scanf("%s",s))
{
if(col[s]!="")
cout<<col[s]<<endl;
else
cout<<"eh\n";
}
return 0;
}

posted on 2011-07-22 15:06  sysu_mjc  阅读(139)  评论(0编辑  收藏  举报

导航