HDU2027单词数(字典树)

本文介绍了一种使用字典树和set数据结构来高效统计文章中不同单词总数的方法,通过AC代码示例展示了如何读取多组数据并输出每组文章的不同单词数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem Description

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

 

Input

有多组数据,每组一行,每组就是一篇小文章。每篇小文章都是由小写字母和空格组成,没有标点符号,遇到#时表示输入结束。

 

Output

每组只输出一个整数,其单独成行,该整数代表一篇文章里不同单词的总数。

Sample Input

you are my friend

#

 

Sample Output

4

统计出现不同的字符个数

用set很简单,字典树也不难

AC代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#include<stdlib.h>
#include<queue>
#include<map>
#include<iomanip>
#include<math.h>
#include<sstream>
using namespace std;
typedef long long ll;
typedef double ld;
const ll inf=0x3f3f3f3f;
const int maxn=2e6+5;
int tree[maxn][30];
bool flag[maxn];
int ans=0,tot=0;
void add(string s)
{
    int root=0,id;
    for(int i=0; i<(int)s.size(); ++i)
    {
        id=s[i]-'a';
        if(!tree[root][id])
            tree[root][id]=++tot;
        root=tree[root][id];
    }
    if(!flag[root])
        ans++;
    flag[root]=1;
}
int main()
{
    string s,tp;
    while(getline(cin,s))
    {
        if(s=="#")
            break;
        stringstream ss(s);
        while(ss>>tp)
        {
            add(tp);
        }
        cout<<ans<<endl;
        ans=0;
        for(int i=0; i<=tot; ++i)
        {
              flag[i]=0;
            for(int j=0; j<27; ++j)
            {
                tree[i][j]=0;
            }
        }///初始化
        tot=0;
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值