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;
}
思想:建立字典树,然后记录通过每一个节点的次数即可。
#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;
}
相关文章推荐
- HDU 1251 统计难题
- HDU 1251 统计难题
- hdu 1251 统计难题(trie树)
- hdu 1251 统计难题
- HDU 1251 统计难题 字典树
- hdu 1251 统计难题
- hdu 1251 统计难题
- HDU 1251统计难题(字典树)
- hdu1251 统计难题 字典树
- HDU 1251 统计难题
- Hdu-1251 统计难题
- hdu 1251统计难题(trie)
- HDOJ 1251 HDU 1251 统计难题 ACM 1251 IN HDU
- HDU 1251 统计难题
- HDU 1251:统计难题
- HDU 1251 统计难题
- HDU-1251-统计难题
- hdu1251——统计难题
- hdu 1251 统计难题//trie树
- HDU 1251 统计难题