hdoj 统计难题

来源:互联网 发布:明朝疆域 知乎 编辑:程序博客网 时间:2024/05/16 15:11
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
 

Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.

注意:本题只有一组测试数据,处理到文件结束.
 

Output
对于每个提问,给出以该字符串为前缀的单词的数量.
 

Sample Input
bananabandbeeabsoluteacmbabbandabc
 

Sample Output
2310
 

可以用hash或字典树
hash思路建立一个vector<vector<string> >然后直接用equal比较就行。建立存有子串hash的复杂度为O(n)。查询的复杂度为O(n)* O(1)= O(n)。
字典树某种程度上也是hash思想,复杂度为O(n*len),实际查询的复杂度只是O(len)。
#include<iostream>#include<vector>#include<stdio.h>#include<algorithm>using namespace std;struct trie{trie *next[26];//字典树int count;//当前字母个数bool exist;//单词的结束标志};void creat(trie *&root){root=new trie;root->count=0;root->exist=false;memset(root->next,0,sizeof(root->next));}void insert(trie *&root,char *w){char *p=w;trie *pt=root;while(*p){int i=*p-'a';if(pt->next[i]==NULL)creat(pt->next[i]);pt=pt->next[i];p++;pt->count+=1;}pt->exist=true;}int search(trie *root,char *w){char *p=w;int i;while(*p){i=*p-'a';root=root->next[i];if(root==NULL)return 0;p++;}return root->count;}int main(){trie *root;creat(root);char a[12];bool flag=false;while(gets(a)){if(flag)cout<<search(root,a)<<"\n";else{if(strlen(a)!=0)insert(root,a);elseflag=true;}}}


原创粉丝点击