poj 2418 Hardwood Species (trie 树)

链接:poj 2418

题意:给定一些树的种类名,求每种树所占的百分比,并按字典序输出

分析:实质就是统计每种树的数量n,和所有树的数量m,

百分比就为 n*100./m

由于数据达到一百万,直接用数组查找肯定超时,

可以用trie树,空间换取时间

注:这题树的品种名除了包括大写字母,小写字母和空格外,还有其他字符,

所以要注意trie树的子结点的个数

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
typedef struct stu
{
    struct stu *next[240]; //注意next数组的个数
    int n;
}node;
struct word
{
    char s[35];
    double r;
}w[10010];
int n,m;
int cmp(struct word s1,struct word s2) //按字典序排序
{
    return strcmp(s1.s,s2.s)<0?1:0;
}
node* creat_node()                //创建结点并初始化
{
    node *p=(node *)malloc(sizeof(node));
    p->n=0;
    memset(p->next,0,sizeof(p->next));
    return p;
}
void trie_insert(node *p,char *s)  //trie的插入
{
    int i;
    char *t=s;
    while(*s!='\0'){
        i=*s;
        if(p->next[i]==0)
            p->next[i]=creat_node();
        p=p->next[i];
        s++;
    }
    if(p->n==0){
        strcpy(w[n].s,t);
        n++;
    }
    p->n++;
}
void trie_search(node *p,char *s,int j)  //查找
{
    int i;
    while(*s!='\0'){
        i=*s;
        p=p->next[i];
        s++;
    }
    w[j].r=(p->n)*100./m;  //算百分比
}
int main()
{
    node *root=NULL;
    int i=0;
    char s[35];
    root=creat_node();
    n=m=0;
    while(gets(s)!=NULL){
        m++;
        trie_insert(root,s);
    }
    sort(w,w+n,cmp);
    for(i=0;i<n;i++){
        trie_search(root,w[i].s,i);
        printf("%s %.4lf\n",w[i].s,w[i].r);
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值