POJ - 2418 Hardwood Species(map,trie,BST)

1、输入若干行树名,输入结束后,按字典序输出树名及其所占百分比。

2、多种方法:map,trie,BST

3、

map:

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

int main(){
    map<string,int>h;
    string s;
    int n;
    n=0;
    while(getline(cin,s)){
        ++n;
        ++h[s];
    }
    map<string,int>::iterator it;
    for(it=h.begin();it!=h.end();++it){
        string name=(*it).first;
        int k=(*it).second;
        printf("%s %.4f\n",name.c_str(),double(k)*100/double(n));
    }
}
View Code

trie:

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

const int MAX=128;
char tree[10005][35];//存储不同的树名
int species=0;//树的种类数目
int totalNum=0;//树的总数目

struct Trie
{
    Trie *next[MAX];
    int num;//出现次数
};
Trie *root=new Trie;

void createTrie(char *str)
{
    ++totalNum;
    int len = strlen(str);
    Trie *p = root, *q;
    for(int i=0; i<len; ++i)
    {
        int id = str[i];
        if(p->next[id] == NULL)
        {
             q = (Trie *)malloc(sizeof(Trie));
            //q = new Trie;
            for(int j=0; j<MAX; ++j){
                q->next[j] = NULL;
                q->num=0;
            }
            p->next[id] = q;
        }
        p = p->next[id];
    }
    if(p->num==0)strcpy(tree[species++],str);
    ++p->num;
}
int findTrie(char *str)
{
    int len = strlen(str);
    Trie *p = root;
    for(int i=0; i<len; ++i)
    {
        int id = str[i];
        p = p->next[id];
        if(p == NULL)   //若为空集,表示不存以此为前缀的串
            return 0;
    }
    return p->num;
}
int cmp(const void *a,const void *b){
    return strcmp((char *)a,(char *)b);//升序
}
int main()
{
    char str[35];
    int i;
    for(i=0; i<MAX; i++){
        root->next[i]=NULL;
        root->num=0;
    }
    while(gets(str)){
        createTrie(str);
    }
    qsort(tree,species,sizeof(tree[0]),cmp);
    for(i=0;i<species;++i)
        printf("%s %.4f\n",tree[i],double(findTrie(tree[i]))/double(totalNum)*100);
    return 0;
}
View Code

BST:

 

posted @ 2015-11-06 12:43  gongpixin  阅读(338)  评论(0编辑  收藏  举报