POJ 2418 字典树

题目链接:http://poj.org/problem?id=2418

题意:给定一堆树的名字,现在问你每一棵树[无重复]的出现的百分比,并按树名的字典序输出

思路:最简单的就是用map来写,关于字典树的解法,因为字典序的先序遍历是排序的,所以只需建好树后先序遍历一下树就可以满足题目要求的输出方式了。

坑点:树名会出现空格,而且题目也没说明可能出现的字符集合,所以树的孩子结点要有128个。 G++无限WA换C++就能AC,这个无解。。。

map:

#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <string>
#include <cstdio>
#include <stdlib.h>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <map>
#include <time.h>
using namespace std;
typedef long long int LL;
char str[50];
map<string, int>word;
int main(){
    int n = 0;
    while (gets(str) != NULL){
        n++; string ss = string(str);
        word[ss]++;
    }
    for (map<string, int>::iterator it = word.begin(); it != word.end(); it++){
        cout << (it->first);
        printf(" %.4lf
", (it->second)*1.0 / n*100.0);
    }
    return 0;
}

字典树:

#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <time.h>
using namespace std;
typedef long long int LL;
const int MAXN = 100000 + 5;
char str[50];
struct Trie{
    int val;
    int child[128];
    Trie(){
        val = 0;
        memset(child, 0, sizeof(child));
    }
}trie[MAXN];
int trieN, n;
void Insert(char *str){
    int d, x = 0;
    for (int i = 0; str[i]; i++){
        d = str[i];
        if (trie[x].child[d] == 0){
            trie[x].child[d] = ++trieN;
        }
        x = trie[x].child[d];
    }
    trie[x].val++;
}
void Search(int u, int len, char *str){
    for (int i = 0; i < 128; i++){
        if (trie[u].child[i]){
            str[len] = i;
            Search(trie[u].child[i], len + 1, str);
        }
    }
    if (trie[u].val){
        str[len] = '';
        printf("%s %.4lf
", str, (trie[u].val*1.0 / n)*100.0);
    }
}
int main(){
    trieN = 0, n = 0;
    while (gets(str) != NULL){
        n++; Insert(str);
    }
    Search(0, 0, str);
    return 0;
}
原文地址:https://www.cnblogs.com/kirito520/p/5732184.html