HDU - 2072 单词数(Trie树)

题目链接

题目大意:给定一篇文章,统计其中不同的单词数目。

思路很清晰,如果用字典树的话,先获取每个单词,插入字典树中,插入的时候作两方面的判断,一是这个单词走的路径是否是新的,二的这个单词是否是某个单词的前缀,如果有一个符合,就说明这个单词是新的单词。

这个题数据有点坑,首先是多组数据,每组一行,然后是每组数据可能存在连续的空格,在获取字符串的时候要注意这个。

详见代码。

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<stdlib.h>
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<stdlib.h>
#include<string.h>
#include<string>
#include<vector>
#include<stack>
#include<queue>
#include<map>
#include<math.h>
#include<set>
using namespace std;
#define INF 1000000
const int maxn=1e5+10;
int tree[maxn][27];
bool isstr[maxn];
int tot;
int Insert(string s)
{
    int notnew=0;//这个单词不存在
    int root=0;
    for(int i=0;i<(int)s.size();i++)
    {
        int id=s[i]-'a';
        if(!tree[root][id])
        {
            notnew=1;//路径不存在实锤
            tree[root][id]=++tot;
        }
        if(i==s.size()-1 && !isstr[tree[root][id]]) notnew=1;//可能是某个词的前缀
        root=tree[root][id];
    }
    isstr[root]=1;
    return notnew;
}

int main()
{
//    ios::sync_with_stdio(false);
//    cin.tie(0);
    string str;
    char ch;
    while(1)
    {
        int sum=0;//表示每篇文章的不同单词数
        memset(tree,0,sizeof(tree));
        memset(isstr,0,sizeof(isstr));
        tot=0;
        while(ch=getchar())
        {
            if(ch=='#') break;
            if(ch!=' ' && ch!='\n')
            {
                str+=ch;
            }
            else
            {
                sum+=Insert(str);
                str.clear();
            }
            if(ch=='\n')
            {
                cout<<sum<<'\n';
                break;
            }
        }
        if(ch=='#') break;
    }
 //   system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值