您的位置:首页 > 其它

HDU 1880 魔咒词典

2012-04-28 19:02 591 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1880

最初的想法直接快排+二分查找

为了练习hash就用hash做了

View Code

#include <cstdio>
#include <cstring>
using namespace std;

const int N=100010,MAXH=100003;
char w0
[25],w1
[85];
int head[2][MAXH],next[2]
;
int n;
int hash(char *key)
{
unsigned int h=0;
while(*key)
{
h=(h<<4)+*key++;
unsigned int g=h&0xf000000L;
if(g) h^=g>>24;
h&=~g;
}
return h%MAXH;
}
void insert(int s,int k)
{
int h=k?hash(w1[s]):hash(w0[s]);
next[k][s]=head[k][h];
head[k][h]=s;
}
void dictionary()
{
const char end[6]="@END@";
memset(head,0,sizeof(head));
memset(next,0,sizeof(next));
n=0;
char s1[25],s2[85];
while(scanf("%s",s1),strcmp(s1,end))
{
n++;
strcpy(w0
,s1);
insert(n,0);
getchar(); gets(s2);
strcpy(w1
,s2);
insert(n,1);
}
}
int find(char *s,int k)
{
int h=hash(s);
int u=head[k][h];
if(k==0) while(u && strcmp(s,w0[u])) u=next[k][u];
else while(u && strcmp(s,w1[u])) u=next[k][u];
return u;
}
void putstr(char *s)
{
for(int i=1;s[i]!=']';i++) putchar(s[i]);
putchar('\n');
}
int main()
{
dictionary();
int T;
scanf("%d",&T); getchar();
while(T--)
{
char s[85];
gets(s);
if(s[0]=='[')
{
int p=find(s,0);
if(p) puts(w1[p]);
else puts("what?");
}
else
{
int p=find(s,1);
if(p) putstr(w0[p]);
else puts("what?");
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: