Problem:
给定一个单词表,再每给一个字符串,就输出它作为前缀的最多次数。
Solution:
标准的字典树模板题;
note:
c++比g++更节省内存,c++A了,但是g++没A。
#include<cstdio>
#include<iostream>
#include<sstream>
#include<cstdlib>
#include<cmath>
#include<cctype>
#include<string>
#include<cstring>
#include<algorithm>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<ctime>
#include<vector>
#include<fstream>
#include<list>
using namespace std;
#define ms(s) memset(s,0,sizeof(s))
typedef unsigned long long ULL;
typedef long long LL;
const double PI = 3.141592653589;
const int INF = 0x3fffffff;
struct node{
node* next[26]; int v;
node(){
v = 1;
for(int i = 0; i < 26; ++i)
next[i] = NULL;
}
};
struct Trie{
node* root;
Trie(){root = NULL;}
void inserts(char str[]){
int len = strlen(str);
if(!root)
root = new node;
node* now = root;
for(int i = 0; i < len; ++i){
int num = str[i]-'a';
if(now->next[num] == NULL)
now->next[num] = new node;
else
++((now->next[num])->v);
now = now->next[num];
}
}
int searchs(char str[]){
int len = strlen(str);
node* now = root;
for(int i = 0; i < len; ++i){
int num = str[i]-'a';
if(now->next[num] == NULL)
return 0;
now = now->next[num];
}
return now->v;
}
};
int main(){
// freopen("E:\\input.txt","r",stdin);
// freopen("E:\\output.txt","w",stdout);
// ios::sync_with_stdio(false);
Trie a;
int ans;
char str[20];
while(gets(str)){
if(str[0] == '\0')
break;
a.inserts(str);
}
while(gets(str)){
ans = a.searchs(str);
printf("%d\n",ans);
}
return 0;
}