您的位置:首页 > 其它

HDU 2072 单词数(Tire 和 set 两解)

2014-06-07 15:14 423 查看
Problem Description

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

Input

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

Output

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

Sample Input

you are my friend
#


Sample Output

4


第一种解法运用字典树,数据量不大,一行大概也就80个字符左右。

思路就是建树,建树的过程中计算不同单词的数量,即判断一下这个单词插入完成后val值是否已经存在,若为正,说明该单词已经存在,若为0 ,说明该单词第一次出现。

#include<stdio.h>
#include<string.h>
char a[110];
char s[100];
int ch[10010][26];
int val[10010] ,sz ,ans;
int id(char c) {
return c-'a';
}
void Inse(char *s , int n ) {
int u=0 ;
for(int i=0;i<n;i++) {
int c=id(s[i]);
if(!ch[u][c]) {
ch[u][c]=sz++;
}
u=ch[u][c];
}
if(val[u] == 0) ans++;
val[u]=1;
}
int main()
{
while(1) {
gets(a);
if(a[0] == '#') break;
int len=strlen(a);
a[len]=' ';
a[len+1]=0;
memset(ch,0,sizeof(ch));
memset(val,0,sizeof(val));
sz=1 ,ans=0;
int k=0;

for(int i=0;a[i];i++) {

if(a[i] != ' ' ) {
s[k++]=a[i];
} else if(s[0] != 0){
//  printf("%s",s);
Inse(s , k);
memset(s,0,sizeof(s));
k=0;
}
}
printf("%d\n",ans);
}
return 0;
}


第二种解法也是刚学习的C++ STL 里的set , 类似数学理的集合,因为集合里每个元素只有一个。
通过这题我也了解了string类和cin的输入到底是怎么回事。。
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <string>
#include <set>
using namespace std;

set <string> dict;

int main()
{
string s,buf;
int ok=0;
while(1) {
getline(cin , s) ;  //从第一个不是空格或回车或Tab开始读取
if(s[0] == '#') break;
stringstream ss(s);
dict.clear();  //清空集合
while( ss >> buf ) dict.insert(buf); //插入到集合
int cnt=0;
for( set<string>::iterator it = dict.begin(); it != dict.end(); it++ ) cnt++; //找到当前集合有多少元素
cout << cnt << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: