标签:字典树
题目:

4 10 20 30 04 5 2 3 4 3 4
1 2
把每个数的按字符存放到树中,如数10,可以看成字符‘10’,‘1’就存放到根节点的第二个子树,而‘0’就存放到第二个子树的第一个子树中,最终第二个子树的第一个子树结点中,数据部分count+1;
注意:01与001在字典树中是不同的,所以要先把前面没用的0去除;
错误分析:创建结点时把T写成Tri根节点了,导致每加入一个数都从头开始;
#include<stdio.h>
#include<cstring>
#include<stdlib.h>
#include<iostream>
using namespace std;
#pragma comment(linker,"/STACK:102400000,102400000")
#define MAX 10
char a[35];
int ans;
struct Tritree //存储结构
{
int count; //标记共同前缀的单词数
Tritree *next[MAX]; //单个字符的可能取值
}*Tri;
Tritree * build_tri() //创建节点
{
Tritree *T=(Tritree *)malloc(sizeof(Tritree));
T->count=0;
for(int i=0;i<MAX;i++)
T->next[i]=NULL;
return T;
}
void insert_tri(char a[]) //把每个字符串插入字典树中
{
Tritree *p=Tri;
for(int i=0;i<strlen(a);i++)
{
int id=a[i]-'0'; //取a的第i个字符,注意题目中只有数字字符
if(p->next[id]==NULL)
p->next[id]=build_tri();
p=p->next[id];
}
p->count++;
ans=max(ans,p->count);
}
void delete_tri(Tritree *T)//释放字典树
{
if(T!=NULL)
{
for(int i=0;i<MAX;i++)
{
if(T->next[i]!=NULL)
delete_tri(T->next[i]);
}
}
free(T);
T=NULL;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
ans=0;
Tri=build_tri();
for(int i=0;i<n;i++)
{
scanf("%s",a);
int j=0;
while(a[j]=='0')j++; //去除数前面的无用‘0’
insert_tri(a+j);
}
printf("%d\n",ans);
delete_tri(Tri);
}
return 0;
}
HDU1800Flying to the Mars(字典树),布布扣,bubuko.com
HDU1800Flying to the Mars(字典树)
标签:字典树
原文地址:http://blog.csdn.net/u010270403/article/details/26579489