题意:
给你一组字符串, 每一行有两个串,a,b;
输入空行结束
给你一个串c,问你在前面的第二列的数组中出没出现过,有的话,输出前面的那个,没有的话输出eh
sscanf函数应用是,把一个串,分割成不同类型的
1. map 2625ms
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<map>
#include<queue>
#include<climits>
#include<list>
#define MULT 20000
using namespace std;
int main()
{
char ls[30], lk[30],lp[30];
map<string,string>mapS;
while(gets(ls))
{
if(strlen(ls)==0)
break;
sscanf(ls,"%s %s",lk,lp);
mapS[lp] = lk;
}
map<string,string>::iterator iter;
while(gets(ls))
{
iter = mapS.find(ls);
if(iter!=mapS.end())
{
cout<<iter->second<<endl;
}
else
printf("eh\n");
}
return 0;
}
2 哈希 813ms#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define mod 2000
int tmp ;
using namespace std;
struct node
{
char s[30];
char a[30];
int next;
}ls[100500];
int head[2500];
int hash_index(char s[])
{
int hash=1;
int len=strlen(s);
for(int i=0; i<len; i++)
hash=(hash*29+s[i]-'a')%mod;
return hash;
}
int main()
{
tmp = 1;
char tr[30], tl[30], to[30];
memset(head,-1,sizeof(head));
while(gets(to))
{
if(strlen(to)==0)
break;
sscanf(to,"%s %s",tl,tr);
int key = hash_index(tr);
if(head[key]==-1)
{
strcpy(ls[tmp].s,tl);
strcpy(ls[tmp].a,tr);
ls[tmp].next = -1;
head[key] = tmp++;
}
else
{
int c = head[key];
while(1)
{
if(ls[c].next!=-1)
c = ls[c].next;
else
break;
}
strcpy(ls[tmp].s,tl);
strcpy(ls[tmp].a,tr);
ls[tmp].next = -1;
ls[c].next = tmp++;
}
}
while(gets(tr))
{
int key = hash_index(tr);
int c = head[key];
if(head[key]==-1)
{
printf("eh\n");
continue;
}
while(c!=-1)
{
if(strcmp(ls[c].a,tr)==0)
{
printf("%s\n",ls[c].s);
break;
}
c = ls[c].next;
}
if(c == -1)
printf("eh\n");
}
return 0;
}
3. 字典树 532ms
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
#include<iostream>
using namespace std;
int top;
struct node
{
int next[30];
int n;
char s[30];
} pos[150500];
char ls[35];
void add(char st[],int flag)
{
int j = 0, len = strlen(st);
int i;
for( i = 0; i < len; i++)
{
int x = st[i]-'a'+1;
if(pos[j].next[x]==0)
pos[j].next[x]=++top;
j = pos[j].next[x];
}
if(flag == 1)
{
if(pos[j].n == 0)
{
pos[j].n = 1;
strcpy(pos[j].s,ls);
}
}
else
{
if(pos[j].n== 0)
printf("eh\n");
else
printf("%s\n",pos[j].s);
}
}
int main()
{
top = 0;
memset(pos,0,sizeof(pos));
char str[35], lk[35];
while(gets(str))
{
if(strlen(str)==0)
break;
sscanf(str,"%s %s",ls,lk);
add(lk,1);
}
while(gets(str))
{
add(str,0);
}
return 0;
}

博客介绍了如何利用字典树数据结构解决POJ-2503 Babelfish的字符串匹配问题。对比了使用map实现的效率(2625ms)和字典树的高效解决方案(532ms)。内容涉及ACM竞赛中的字符串处理技巧以及scanf函数的应用。
854

被折叠的 条评论
为什么被折叠?



