zoukankan      html  css  js  c++  java
  • POJ

    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
    ",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
    ",tree[i],double(findTrie(tree[i]))/double(totalNum)*100);
        return 0;
    }
    View Code

    BST:

  • 相关阅读:
    【LeetCode】048. Rotate Image
    【LeetCode】036. Valid Sudoku
    【LeetCode】060. Permutation Sequence
    【LeetCode】001. Two Sum
    【LeetCode】128. Longest Consecutive Sequence
    【LeetCode】081. Search in Rotated Sorted Array II
    【LeetCode】033. Search in Rotated Sorted Array
    顺时针打印矩阵
    矩形覆盖
    二维数组中的查找
  • 原文地址:https://www.cnblogs.com/gongpixin/p/4942267.html
Copyright © 2011-2022 走看看