题目大意:中文题,不解释。
题目分析:字典树水过~
详情请见代码:
#include <iostream>
#include<cstdio>
#include<map>
#include<string>
#include<cstring>
#include<cstdlib>
#include<set>
using namespace std;
typedef struct node
{
struct node *next[26];
int end;
}tree;
char s[100005];
int len;
int deep;
int cnt;
void init(tree *t)
{
t->end = 0;
int i;
for(i = 0;i < 26;i ++)
t->next[i] = NULL;
}
void del(tree *t)
{
int i;
for(i = 0;i < 26;i ++)
if(t->next[i] != NULL)
del(t->next[i]);
free(t);
}
void build(tree *t,int id)
{
if(t->next[s[id] - 'a'] == NULL)
{
t->next[s[id] - 'a'] = (tree *)malloc(sizeof(tree));
init(t->next[s[id] - 'a']);
}
if(s[id + 1] == ' ' || s[id + 1] == '\0')
{
if(t->next[s[id] - 'a']->end == 0)
{
t->next[s[id] - 'a']->end = 1;
cnt ++;
}
deep = id + 1;
return;
}
else
build(t->next[s[id] - 'a'],id + 1);
}
int main()
{
int i;
tree *root = NULL;
while(gets(s) && strcmp(s,"#") != 0)
{
cnt = 0;
root = (tree *)malloc(sizeof(tree));
init(root);
len = strlen(s);
int flag;
for(i = 0;i < len;i ++)
{
if(s[i] == ' ')
{
while(s[i] == ' ')
i ++;
i --;
}
else
{
deep = 0;
build(root,i);
// printf("deep:%d\n",deep);
i = (deep - 1);
}
}
printf("%d\n",cnt);
del(root);
}
return 0;
}
//0MS 332K
这题数据应该很弱,字典树竟然只花了332K。。。
其实此题还有更简单解法,可以用STL的set水过~
详情请见代码:
#include <iostream>
#include<cstdio>
#include<map>
#include<string>
#include<cstring>
#include<cstdlib>
#include<set>
using namespace std;
set<string> lcm;
string s;
char str[100005];
char tmp[100005];
int main()
{
int i,j;
while(gets(str),strcmp(str,"#") != 0)
{
lcm.clear();
i = 0;
while(str[i] == ' ')
i ++;
j = 0;
//printf("len:%d\ni:%d\n",strlen(str),i);
for(;i < strlen(str);i ++)
{
if(str[i] == ' ')
{
tmp[j] = '\0';
s = tmp;
lcm.insert(s);
j = 0;
while(str[i] == ' ')
i ++;
i --;
}
else
tmp[j ++] = str[i];
}
if(j)
{
s = tmp;
lcm.insert(s);
}
printf("%d\n",lcm.size());
}
return 0;
}
//0MS 364K