POJ 2418 Hardwood Species(字典树)

来源:互联网 发布:陈丹丹淘宝店叫什么 编辑:程序博客网 时间:2024/06/05 02:38

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 i,l=strlen(s);    for(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(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;}



0 0