单词数

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

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

you are my friend
#

Sample Output

4

读取数据有点烦,其他的就是字典树的应用了,但是用set肯定也可以,还自动去重.

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int tree[5000][26];
 4 int num[5000];
 5 int pos = 1;
 6 int ans = 0;
 7 
 8 void insert(string s){
 9     int root = 0;
10     for(int i=0;i<s.length();i++){
11         int n = s[i]-'a';
12         if(!tree[root][n]){
13             tree[root][n] = pos++;
14         }
15         root = tree[root][n];
16     }
17     if(num[root]==0&&root!=0){
18         ans++;
19         num[root] = 1;
20     }
21 }
22 
23 
24 int main() {
25     ios::sync_with_stdio(false);
26     cin.tie(0);
27     cout.tie(0);
28     char s[500];
29     while(gets(s)){
30         memset(tree,0,sizeof(tree));
31         memset(num,0,sizeof(num));
32         if(s[0]=='#')
33             break;
34         string ss;
35         for(int i=0;i<strlen(s);i++){
36             if(s[i]!=' '){
37                 ss+=s[i];
38             }else{
39                 if(ss!="")
40                     insert(ss);
41                 ss = "";
42             }
43         }
44         if(ss!="")
45             insert(ss);
46         cout<<ans<<endl;
47         ans = 0;
48 
49     }
50 
51     return 0;
52 }

猜你喜欢

转载自www.cnblogs.com/zllwxm123/p/9293798.html
今日推荐