您的位置:首页 > 其它

HDU 1800 Flying to the Mars Trie或者hash

2013-12-29 10:27 309 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1800

题目大意:

又是废话连篇

给你一些由数字组成的字符串,判断去掉前导0后那个字符串出现频率最高。

一开始敲hash数组开大点嘛。。TLE,开小WA。。肯定是我hash函数写得不好。QAQ

然后我就直接上字典树了。。。

再然后此题的哈希我问了大牛他是直接存hash值我是存个数。。。然后我就牺牲了

然后我又敲了一遍,然后就AC了。

然后就没有然后了。

方法一:字典树Trie

#include<cstdio>
#include<cstring>
struct node
{
	char c;
	int cnt;
	node *next[10];
	node()
	{
		cnt=0;
		for(int i=0;i<10;i++)
			next[i]=NULL;
	}
};
struct Trie
{
	node * root;
	int insert(char *s)
	{
		while(*s=='0')
			s++;
		int len=strlen(s);
		node *cur=root;
		for(int i=0;i<len;i++)
		{
			int id=s[i]-'0';
			if(cur->next[id]==NULL)
			{
				node *temp=new node;
				temp->c=s[i];
				cur->next[id]=temp;

			}
			cur=cur->next[id];
		}

		return ++cur->cnt;
	}
}trie;

int main()
{
	int n;
	while(~scanf("%d",&n))
	{
		trie.root=new node;
		char temp[32];
		int ans=1;
		for(int i=0;i<n;i++)
		{
			scanf("%s",temp);
			int cnt=trie.insert(temp);
			if(ans < cnt)
				ans=cnt;
		}
		printf("%d\n",ans);
	}

	return 0;
}


方法二:hash

关于hash函数选取,选择比给定的个数大的素数就可以了。要素数,才能减少冲突!

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long LL;
const int MAXN=3010;
LL hash_id[MAXN]; 

LL insert(char *s)
{
   while(*s=='0')
	   s++;

   LL id=0;
   for(;*s!='\0';s++)
	   id=id * 11 + *s-'0';

   return id;
}

int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        char temp[32];
        for(int i=0;i<n;i++)
        {
            scanf("%s",temp);
            hash_id[i]=insert(temp);
        }
		sort(hash_id,hash_id+n);
		int ans,cur;
		ans=cur=1;

		for(int i=1;i<n;i++)
		{
			if(hash_id[i]==hash_id[i-1])
				cur++;
			else 
			{
				cur=1;
			}
			if(cur > ans)
				ans=cur;
		}

        printf("%d\n",ans);
    }

    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: