POJ 2418 Hardwood Species(trie的串排序运用)

题意:输入众多字符串(中间有空格),按字典序输出,且输出每个字符串所占整个字符串数量的百分比

思路:用字典树的先序遍历,遍历到字符串的末尾便输出并算出百分比即可

这题同样用C++stl map 可以很好解决,但毕竟题目是字典序,比如逆序就字典树同样可以解决

//1632K	782MS
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
struct trie{
    int cnt;
    char str[35];
    trie *child[127];
    trie(){
        cnt=0;
        for(int i=0;i<127;i++)
            child[i]=NULL;
    }
};
trie *root=new trie;
trie *cur,*newnode;
int num;
void Insert(char *str){
    cur=root;
    int len=strlen(str);
    for(int i=0;i<len;i++){
        int m=str[i];
        if(cur->child[m])
            cur=cur->child[m];
        else {
            newnode=new trie;
            cur->child[m]=newnode;
            cur=newnode;
        }
    }
    cur->cnt++;
    strcpy(cur->str,str);
}
void dfs(trie *rt){ /先序遍历
    if(rt->cnt){
        printf("%s %.4f\n",rt->str,100.0*rt->cnt/(double)num);
    }
    for(int i=1;i<=126;i++)
        if(rt->child[i]!=NULL)
        dfs(rt->child[i]);
}
int main(){
    char tmp[35];
    while(gets(tmp)!=NULL){
        num++;
        Insert(tmp);
    }
    dfs(root);
    return 0;
}

map:

//408K	3032MS
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<map>
#include<string>
using namespace std;
map<string ,int > all;
int cnt;
int main(){
   // freopen("1.in","r",stdin);
    
    string s;
    while(getline(cin,s)){
        all[s]++;
        cnt++;
    }
    for(map<string,int>::iterator it=all.begin();it!=all.end();it++){
        cout<<it->first;
        printf(" %.4f\n",100.0*it->second/(double)cnt);
    }
    return 0;
}
时间大增...

然后我用gets读入避免用cin读入,在把字符数组复制成string试了一发,时间缩短一半:(果然cin酷炫)

//412K	1500MS
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<map>
#include<string>
using namespace std;
map<string ,int > all;
int cnt;
int main(){
    //freopen("1.in","r",stdin);
    char tmp[40];
    string s;
    while(gets(tmp)!=NULL){
        s=tmp;
        all[s]++;
        cnt++;
    }
    for(map<string,int>::iterator it=all.begin();it!=all.end();it++){
        cout<<it->first;
        printf(" %.4f\n",100.0*it->second/(double)cnt);
    }
    return 0;
}


你可能感兴趣的:(POJ 2418 Hardwood Species(trie的串排序运用))