--------刚刚校赛被学弟无情虐了一番,于是回到寝室躲到角落找个水题来缓解下心中愤闷
《单词数》 这题用的字典树做的,wa了好多次,感觉后台数据有点点问题。。 题意很简单了,就素从一篇长文中找出有多少种单词。。字典树insert函数稍作修改就可以, 就是最后单词尾节点如果从来没被赋值成1过(就是字典树没添加过这个单词)就+1;
字典树的意思就是先给一个根节点,然后顺着这条根节点往下连接儿子节点的那条边作为单词的一个字母,如果存在这个字母就下去找那个儿子节点,然后同理找下一个字母。不存在这个字母的话,根节点就再生一个儿子,然后继续不断地生..查找同理,字母不存在就说明没这个单词
本题水代码
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <math.h>
#include <algorithm>
using namespace std;
char s[1000000+5];
char s2[1000000+5];
int ch[1000000+5][26];
int val[1000000+5], tmp, ans;
void insert(char *a)
{
int rt = 0;
for (int i = 0; a[i]; i++)
{
int c = a[i] - 'a';
if (ch[rt][c] == 0)
{
val[tmp] = 0;
//memset(ch[rt], 0, sizeof (ch[rt]));这句话去掉感觉完全没问题
ch[rt][c] = tmp++;
}
rt = ch[rt][c];
}
if (val[rt] == 0) ans++;
val[rt] = 1;
}
int main()
{
while (gets(s) && strcmp(s, "#"))
{
int i, j, top = 0;
tmp = 1, ans = 0;
val[0] = 0;
memset(ch[0], 0, sizeof(ch[0]));
for (i = 0; i <= strlen(s); i++)
{
if (s[i] >= 'a' && s[i] <= 'z')
//如果写成if (s[i] != ' ' && s[i] != '\0')就不行,不是说好的只有空格和小字母吗?
s2[top++] = s[i];
else
{
if (top != 0)
{s2[top] = '\0';
top = 0;
insert(s2);}
}
}
printf("%d\n", ans);
}
return 0;
}