题目大意:给定一篇文章,统计其中不同的单词数目。
思路很清晰,如果用字典树的话,先获取每个单词,插入字典树中,插入的时候作两方面的判断,一是这个单词走的路径是否是新的,二的这个单词是否是某个单词的前缀,如果有一个符合,就说明这个单词是新的单词。
这个题数据有点坑,首先是多组数据,每组一行,然后是每组数据可能存在连续的空格,在获取字符串的时候要注意这个。
详见代码。
#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;
}