您的位置:首页 > 其它

HDU 1251 统计难题

2017-02-21 19:45 232 查看
题意:Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).



思想:建立字典树,然后记录通过每一个节点的次数即可。

#include<iostream>
#include<cstring>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
struct node
{
struct node *next[26];
int cnt;
node()
{
for(int i=0;i<26;i++)
{
next[i]=NULL;
}
cnt=0;
}
}root;

void Insert(char *s)
{
int len=strlen(s);
node *cur=&root;

for(int i=0;i<len;i++)
{
if(cur->next[s[i]-'a']==NULL)
{
cur->next[s[i]-'a']=new node;
}
cur=cur->next[s[i]-'a'];
cur->cnt++;
}
}

int search(char *s)
{
struct node *cur=&root;
int len=strlen(s);
for(int i=0;i<len;i++)
{
if(cur->next[s[i]-'a']!=NULL)
{
cur=cur->next[s[i]-'a'];
}
else
{
return 0;
}
}
return cur->cnt;
}

int main()
{
char s[11];
while(gets(s))
{
if(strlen(s)==0) break;
Insert(s);
}

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