您的位置:首页 > 其它

poj 3087 模拟(ELFHash模版,字符串哈希)

2012-10-19 16:51 375 查看
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

#define MAXN 102

int N,C;
char s1[MAXN],s2[MAXN],s12[MAXN<<1],ans[MAXN<<1];

//*****************ELFhash***********
#define HASH 9901
char table[9901][MAXN];
int len;
int ELFHash(char a[MAXN])
{
int h = 0;
int x  = 0;
for(int i=0;i<len;++i)
{
h = (h << 4) + (a[i]);
if ((x = h & 0xF0000000L) != 0)
{
h ^= (x >> 24);
h &= ~x;
}
}
return h % HASH;
}
bool is_in(char a[])    //ELFHash函数对字符串判重,没有的时候插入
{
int i=ELFHash(a);
while(strlen(table[i])>0&&strcmp(a,table[i])!=0)
i=(i+1)%HASH;
if(strlen(table[i])==0)
{
strcpy(table[i],a);
return false;
}
return true;
}
//***********************************

int main()
{
scanf("%d",&N);
for(int cas=1;cas<=N;cas++)
{
scanf("%d",&C);getchar();
len=C*2;
memset(s1,0,sizeof(s1));
memset(s2,0,sizeof(s2));
memset(s12,0,sizeof(s12));
memset(ans,0,sizeof(ans));
memset(table,0,sizeof(table));
gets(s1);
gets(s2);
gets(ans);
printf("%d ",cas);
int step=0;
while(1)
{
step++;
for(int i=0;i<len;i+=2)
s12[i]=s2[i/2];
for(int i=1;i<len;i+=2)
s12[i]=s1[i/2];
s12[len]='\0';
//cout<<s1<<endl;
//cout<<s2<<endl;
if(strcmp(ans,s12)==0)
{
printf("%d\n",step);
break;
}
else if(is_in(s12))
{
printf("-1\n");
break;
}
for(int i=0;i<C;i++)
s1[i]=s12[i];
for(int i=0;i<C;i++)
s2[i]=s12[i+C];
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: