很裸的字典树,用stl和Hash也能过,不过字典树效率高些。
还有一篇用Hash写的,用的是最常用的ELF。
直接上代码了。
字典树:
#include<iostream>
using namespace std;
struct dictree
{
struct dictree * child[10];
int count;
}*root;
char key[31];
int n;
int zero;
inline void create();
inline void Delete(struct dictree *tree);
inline int insert(char *str);
int main()
{
int MAX,temp;
while(cin>>n)
{
gets(key);
root=new struct dictree;
zero=0;
MAX=0;
create();
for(int i=0;i<n;i++)
{
gets(key);
temp=insert(key);
if(MAX<temp)
MAX=temp;
}
cout<<MAX<<endl;
Delete(root);
}
return 0;
}
inline void create()
{
for(int i=0;i<10;i++)
{
root->child[i]=NULL;
}
}
inline void Delete(struct dictree *tree)
{
for(int i=0;i<10;i++)
{
if(tree->child[i]!=NULL)
Delete(tree->child[i]);
}
delete tree;
}
inline int insert(char *str)
{
int k,len=strlen(str);
k=-1;
for(int i=0;i<len;i++)
{
if(str[i]!='0')
{
k=i;
break;
}
}
if(k==-1)
return ++zero;
struct dictree *current,*newnode;
current=root;
for(i=k;i<len;i++)
{
if(current->child[str[i]-'0']!=NULL)
current=current->child[str[i]-'0'];
else
{
newnode= new struct dictree;
newnode->count=0;
for(int j=0;j<10;j++)
{
newnode->child[j]=NULL;
}
current->child[str[i]-'0']=newnode;
current=newnode;
}
}
current->count++;
return current->count;
}
Hash
#include<iostream>
using namespace std;
const int MAX=7001;
int ELFhash(char *str);
int hashit(int k);
int hash[MAX];
int count[MAX];
int main()
{
int n;
char temp[31];
int h,g;
int ans;
while(scanf("%d",&n)!=EOF)
{
ans=0;
memset(count,0,sizeof(count));
for(int i=0;i<n;i++)
{
scanf("%s",&temp);
h=ELFhash(temp);
g=hashit(h);
count[g]++;
hash[g]=h;
if(count[g]>ans)
ans=count[g];
}
cout<<ans<<endl;
}
return 0;
}
int ELFhash(char * str)
{
unsigned int hash=0;
unsigned int x=0;
while(*str=='0')
str++;
while(*str)
{
hash=hash+(hash<<4)+(*str++);
x=hash & 0xf0000000L;
if(x>0)
{
x=x>>24;
hash=hash^x;
hash=hash&(~x);
}
}
return hash & 0x7FFFFFFF;
}
int hashit(int k)
{
int t=k%MAX;
if(t<0)
t+=MAX;
while(count[t]!=0 && hash[t]!=k)
{
t=(t+1)%MAX;
}
return t;
}
分享到:
相关推荐
hdu 1166线段树
hdu 1166线段树代码
HDUACM2010版_14)Hash及应用HDUACM2010版_14)Hash及应用HDUACM2010版_14)Hash及应用HDUACM2010版_14)Hash及应用
HDU的1250,主要是利用高精度加法,但是代码有点繁琐,效率不是很高
杭电ACMhdu1163
HDU1059的代码
hdu1001解题报告
hdu 1574 passed sorce
HDU的一题........HDU DP动态规
hdu2101AC代码
hdu acm 教案 搜索入门 hdu acm 教案 搜索入门
搜索 dfs 解题代码 hdu1241
hdu 5007 Post Robot 字符串枚举。 暴力一下就可以了。
hdu acm 教案 动态规划(1) hdu acm 教案 动态规划(1)
NULL 博文链接:https://128kj.iteye.com/blog/1734821
自己做的HDU ACM已经AC的题目
HDU最全ac代码
ACM HDU题目分类,我自己总结的大概只有十来个吧
hdu动态规划算法集锦