poj 2418 Hardwood Species

题目意思:给你若干棵树,问你每种树出现的概率;

解题思路:(1)trie树 ,不过这题的输出很让人纠结,它是按ACSII表的顺序输出的,本以为大小写字母再加上一个空格,开53个数组就够了,但是不幸的WA了, 后来看了别人的解题报告,直接开到了95,改了一下就过了~

(2)stl的map容器。不过这个很慢,可以过,但是没法很trie树的比,一个700+ms,一个3000+ms。呃,第一次用map,权当练练手。

trie树:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <queue>
#define  maxx  95
using namespace std ;

struct node
{
    int num ;
    struct node *next[maxx] ;
}*s ;
int sum ;
char str[35] ;

struct node *creat ( )
{
    struct node *p ;
    p = ( struct node *) malloc ( sizeof ( struct node ));
    for ( int i = 0 ; i < maxx ; i++ )
    p->next[i] = NULL ;
    p->num = 0 ;
    return p ;
}

void insert ( char str[] )//建树
{
    int i , x ;
    struct node *p , *q ;
    p = s ;
    for ( i = 0 ; str[i] != '\0' ; i++ )
    {
        x = str[i] - ' ' ;
        if ( p->next[x] == NULL )
        {
            q = creat( ) ;
            p->next[x] = q ;
            p = q;
        }
        else
        p = p->next[x] ;
    }
    p->num++;
}

void find ( struct node *p , int step )//查找
{
    for ( int i = 0 ; i < maxx ; i++ )
    {
        if ( p->next[i] != NULL && p->num == 0)
        {
            str[step] = i + ' ' ;//将查找到的字符存起来
            find ( p->next[i] , step + 1 );
        }
        else if ( p->num != 0 )//如果p->num 不为0的话输出
        {
            str[step] = '\0' ;
            printf ( "%s %.4lf\n" , str , ( double )p->num / sum * 100 );
            return ;
        }
    }
}

int main()
{
    s = creat( );
    for ( sum = 0 ; gets( str ) ; sum++ )
    {
        insert ( str );
    }
    find ( s , 0 );
    return 0 ;
}

map容器的:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <map>
#include <string>
using namespace std ;

int main()
{
    string str ;
    map<string , double>mm;
    map<string , double>::iterator s ;
    int sum = 0 ;
    while ( getline ( cin , str ))
    {
        mm[str]++;
        sum++ ;
    }
    for ( s = mm.begin() ; s != mm.end() ; s++ )
    {
        cout<<s->first;
        printf ( " %.4lf\n" , s->second * 100 / sum );
    }
    return 0 ;
}

转载于:https://www.cnblogs.com/misty1/archive/2012/05/31/2528855.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值