Problem Description
随着卫星成像技术的应用,自然资源研究机构可以识别每一个棵树的种类。请编写程序帮助研究人员统计每种树的数量,计算每种树占总数的百分比。
Input
输入一组测试数据。数据的第1行给出一个正整数N (n <= 100000),N表示树的数量;随后N行,每行给出卫星观测到的一棵树的种类名称,树的名称是一个不超过20个字符的字符串,字符串由英文字母和空格组成,不区分大小写。
Output
按字典序输出各种树的种类名称和它占的百分比,中间以空格间隔,小数点后保留两位小数。
Sample Input
2 This is an Appletree this is an appletree
Sample Output
this is an appletree 100.00%
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int ii;
char zhan[30];
struct node
{
char ch;//此节点所存字母
int num;//子节点个数
int jie;//在此处结束的字符串个数
struct node * next[30];//子节点地址(若存在大小写加数字需要增加空间)
};
int cmp(struct node * a,struct node * b)
{
return a->ch<b->ch;
}//按字典序排列子节点
void create(struct node * head,char * str)//建树
{
struct node * p;
int i,j,flag,len;
p=head;
len=strlen(str);
for(i=0; i<len; i++)
{
flag=0;//初始化为子节点中不存在该字符
for(j=1; j<=p->num; j++)
{
if(p->next[j]->ch==str[i])
{
flag=1;//若存在该字符,则标记
if(i==len-1)
{
p->next[j]->jie++;//若为一个字符串的最后一个,将jie++
//jie代表了这个字符串有几个相同的字符串
}
else
{
p=p->next[j];//若不为最后一个,则继续下一个匹配
}
break;
}
}
if(flag==0)//若没有匹配到,则创立一个新的子节点
{
p->num++;//将p的子节点数增加一个
p->next[p->num]=(struct node *)malloc(sizeof(struct node));
//创立一个新空间
p->next[p->num]->ch=str[i];
p->next[p->num]->num=0;
p->next[p->num]->jie=0;//初始化
if(i==len-1)
{
p->next[p->num]->jie++;//若为最后一个,在此结束的字符串数加一个
}
else
{
p=p->next[p->num];//若不为最后一个,那么继续下一个建树
}
}
}
}
void dfs(struct node * root,char * zhan,int ii)//搜索
{
struct node * p;
p=root;//从根节点开始
int i,j;
sort(p->next+1,p->next+1+p->num,cmp);//按字典序排序(个别题目需要)
for(i=1;i<=p->num;i++)
{
zhan[++ii]=p->next[i]->ch;
if(p->next[i]->jie!=0)//若在此处存在一个字符串,输出
{
for(j=1;j<=ii;j++)
{
printf("%c",zhan[j]);
}
printf("\n");
}
dfs(p->next[i],zhan,ii);//深搜
ii--;
}
}
int main()
{
int i,n;
char str[30];
int ii;
char zhan[30];
scanf("%d",&n);
ii=0;
getchar();
struct node * head;
head=(struct node *)malloc(sizeof(struct node));
head->num=0;
head->jie=0;//头节点初始化
for(i=1; i<=n; i++)
{
gets(str);
create(head,str);//建树
}
dfs(head,zhan,ii);//查找
return 0;
}