字典树 (HDU 2072)

lily的好朋友xiaoou333最近很空,他想了一件没有什么意义的事情,就是统计一篇文章里不同单词的总数。下面你的任务是帮助xiaoou333解决这个问题。

Input有多组数据,每组一行,每组就是一篇小文章。每篇小文章都是由小写字母和空格组成,没有标点符号,遇到#时表示输入结束。Output每组只输出一个整数,其单独成行,该整数代表一篇文章里不同单词的总数。Sample Input
you are my friend
#
Sample Output
4

题目分析 : 这题用 map 写时很方便的,为了联系字典树,用字典树写了一发。

代码示例 :
#define ll long long
const int maxn = 1e5+5;
const double pi = acos(-1.0);
const int inf = 0x3f3f3f3f;

char s[maxn], f[100];
struct node
{
    int next[26];
    int val;
}t[maxn];
int rt;
int ans = 0, k;

void build(){
    int u = 0, v;
    
    for(int i = 0; i < k; i++){
        v = f[i] - 'a';
        if (!t[u].next[v]){
            t[u].next[v] = rt++;
        }
        u = t[u].next[v];
    }
    t[u].val++;
    if (t[u].val == 1) ans++;
}

int main() {
    //freopen("in.txt", "r", stdin);
    //freopen("out.txt", "w", stdout);
    
    while(gets(s+1)){
        if (s[1] == '#') break;
        
        int len = strlen(s+1);
        memset(t, 0, sizeof(t));
        rt = 1;
        s[len+1] = ' ';
        k = 0; ans = 0;
        for(int i = 1; i <= len+1; i++){
            if (s[i] != ' '){
                f[k++] = s[i];
            }
            else {
                if (k != 0)build();
                k = 0;
            }
        }
        cout << ans << endl;
    }
    return 0;
}

 

posted @ 2018-03-13 17:09  楼主好菜啊  阅读(125)  评论(0编辑  收藏  举报