您的位置:首页 > 其它

HDU 2072 - 单词数 (Trie)

2014-07-08 20:52 375 查看

单词数

Time Limit: 1000/1000 MS (Java/Others)

Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 27356 Accepted Submission(s): 6440



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

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

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

[align=left]Sample Input[/align]

you are my friend
#


[align=left]Sample Output[/align]

4


[align=left]Author[/align]
Lily

[align=left]Source[/align]
浙江工业大学网络选拔赛

[align=left]Recommend[/align]
linle

思路:

Trie 

WA了好多次 开始的时候用sscanf 然后每次读取一个word的时候加上这个word的长度 这有忽略了中间的空格问题

然后改为自己判断

还有 输入有可能是一个只有空格的行

#include <stdio.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <string>
#include <map>
#include <cmath>
#include <queue>
#include <set>

using namespace std;

//#define WIN
#ifdef WIN
typedef __int64 LL;
#define iform "%I64d"
#define oform "%I64d\n"
#define oform1 "%I64d"
#else
typedef long long LL;
#define iform "%lld"
#define oform "%lld\n"
#define oform1 "%lld"
#endif

#define S64I(a) scanf(iform, &(a))
#define P64I(a) printf(oform, (a))
#define S64I1(a) scanf(iform1, &(a))
#define P64I1(a) printf(oform1, (a))
#define FOR(i, s, t) for(int (i)=(s); (i)<(t); (i)++)

const int INF = 0x3f3f3f3f;
const double eps = 10e-9;
const double PI = (4.0*atan(1.0));

const int maxsize = 200000;

struct Trie {
int size;
int val[maxsize];
int ch[maxsize][26];
Trie() {
clear();
}
void clear() {
size = 1;
memset(ch[0], 0, sizeof(ch[0]));
memset(val, 0, sizeof(val));
}
int idx(char c) {
return c - 'a';
}
bool insert(const char * s) {
int len = strlen(s);
int u = 0;
for(int i=0; i<len; i++) {
int c = idx(s[i]);
if(!ch[u][c]) {
memset(ch[size], 0, sizeof(ch[size]));
val[size] = 0;
ch[u][c] = size++;
}
u = ch[u][c];
}
if(val[u]) return false;
val[u] = 1;
return true;
}
};

char s[1000];
Trie trie;
char word[1000];

int main() {

while(gets(s) && s[0] != '#') {
trie.clear();
int len = strlen(s);
int ans = 0;
int p = 0;
while(p < len) {
int wn = 0;
while(p < len && s[p] < 'a' || s[p] > 'z') p++;
while(p < len && s[p] >= 'a' && s[p] <= 'z') word[wn++] = s[p++];
word[wn] = '\0';
// printf("=>%s\n", word);
if(wn > 0 && trie.insert(word)) {
ans++;
// printf("in=>%s\n", word);
}
}
printf("%d\n", ans);
memset(s, 0, sizeof(s));
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: