`
thecloud
  • 浏览: 877353 次
文章分类
社区版块
存档分类
最新评论

hdu 1800 字典树或Hash

 
阅读更多

很裸的字典树,用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;
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics