POJ2418 Hardwood Species(字典树)

Hardwood Species

题目链接:

http://poj.org/problem?id=2418

解题思路:

字典树的题,不过要用到dfs的一点小技巧;当然用map也可以做!

AC代码(map):

#include <iostream>
#include <cstdio>
#include <string>
#include <map>
#include <algorithm>
using namespace std;

const int maxn = 1000010;
string str,name[10010];
int ans = 0,tot = 0;

int main(){

    string str;
    map<string,int> tree;
    while(getline(cin,str) && str!=""){
        if(tree.find(str) == tree.end()){
            tree[str] = 1;
            name[ans++] = str;
        }
        else
            tree[str]++;
        tot++;
    }
    sort(name,name+ans);
    for(int i = 0; i < ans; i++)
        printf("%s %.4lf\n",name[i].c_str(),tree[name[i]]*1.0/tot*100);
    return 0;
}

AC代码(字典树):

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

struct node{
    int cnt;
    struct node *next[130];
    node(){
        cnt = 0;
        memset(next,0,sizeof(next));
    }
};

node *root = NULL;
int n;

void build(char *s){
    node *p = root,*tmp;
    int l=strlen(s);
    for(int i = 0; i < l; i++){
        if(p->next[s[i]] == NULL){
            tmp = new node;
            p->next[s[i]] = tmp;
        }
        p = p->next[s[i]];
    }
    p->cnt++;
}

void dfs(node *root){
    static char word[31];
    static int pos;
    int i;
    if(root->cnt){   //如果cnt不为0,则肯定找到了一个单词
        word[pos] = '\0';
        if(word[0])
            printf("%s %.4lf\n",word,root->cnt*100*1.0/n);
    }
    for(int i = 0; i < 130; i++){
        if(root->next[i]){
            word[pos++] = i;
            dfs(root->next[i]);
            pos--;
        }
    }
}

int main(){
    char str[31];
    n = 0;
    root = new node;
    while(gets(str) && str!=""){
        build(str);
        n++;
    }
    dfs(root);
    return 0;
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值