梦,才是最真的现实

导航

HDU 1800 贪心

这个题目不同于导弹拦截,这个可以调整顺序的,所以我们可以通过统计每个数字的出现次数,出现次数最多的就是ANS

比如 1 2 4 5 4 ,其中4出现了两次,这个次数是最多的了,所以答案就是2

由于数字区间高达三十位数,用普通的区间查找绝对TLE,这个时候,用字典树是个好选择,统计下每个字符串的出现次数是字典树的典型应用

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define val 3005
struct Dictree
{
	int cnt;
	struct Dictree *next[10];
}*root;
void create_tree();
void insert(char*);
void dfs(struct Dictree*);
int ans;
int main()
{
	int n,i,j;
	char s[35];
	while(scanf("%d",&n)!=EOF)
	{
		ans=0;
		create_tree();
		for(i=0;i<n;i++)
		{
			scanf("%s",s);
			j=0;
			while(s[j]=='0') j++;//去掉前导0
			insert(s+j);
		}
		dfs(root);
		printf("%d\n",ans);
	}
	return 0;
}
void create_tree()
{
	int i;
	root=(struct Dictree*)malloc(sizeof(struct Dictree));
	root->cnt=0;
	for(i=0;i<10;i++)
		root->next[i]=NULL;
}
void insert(char *s)
{
	int i,j;
	struct Dictree *p,*t;
	p=root;
	for(i=0;s[i];i++)
	{
		if(p->next[s[i]-'0']==NULL)
		{
			t=(struct Dictree*)malloc(sizeof(struct Dictree));
			t->cnt=0;
			for(j=0;j<10;j++)
				t->next[j]=NULL;
			p->next[s[i]-'0']=t;
		}
		p=p->next[s[i]-'0'];
	}
	p->cnt++;
//	if(p->cnt>ans) ans=p->cnt;
}
void dfs(struct Dictree *p)
{
	int i;
	if(p->cnt>ans) ans=p->cnt;
	for(i=0;i<10;i++)
		if(p->next[i]!=NULL)
			dfs(p->next[i]);
}


posted on 2012-08-19 19:12  梦,才是最真的现实  阅读(125)  评论(0编辑  收藏  举报