字典樹練習(一)hihocoder 1014(求相同前綴的數(shù)目)
來源:程序員人生 發(fā)布時間:2015-05-21 08:26:22 閱讀次數(shù):3166次
題目鏈接:
http://hihocoder.com/problemset/problem/1014
題意:
給定n個單詞,然后我們構成1個字典樹,然后再給你m個串,求有多少個單詞是以這個串為前綴的。
代碼以下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 100010;
const int max_size = 30;
int id(char c){
return c-'a';
}
struct Trie{
Trie *ch[max_size];
int num;
Trie(){
num = 0;
for(int i=0;i<max_size;i++)
ch[i]=NULL;
}
}*root;
void insert_str(char *s){
Trie *p = root;
p->num++;
for(int i=0; p&&s[i] ; i++){
int u = id(s[i]);
if(p->ch[u]==NULL)
p->ch[u] = new Trie;
p=p->ch[u];
p->num++;
}
}
int find_str(char *s){
Trie *p = root;
for(int i=0;p&&s[i];i++){
int u = id(s[i]);
if(p->ch[u]==NULL) return 0;
p=p->ch[u];
}
return p->num;
}
int main()
{
char s[12];
int n, m;
while(~scanf("%d", &n))
{
root = new Trie;
while(n--){
scanf("%s", s);
insert_str(s);
}
scanf("%d", &m);
while(m--){
scanf("%s", s);
printf("%d
", find_str(s));
}
}
return 0;
}
生活不易,碼農辛苦
如果您覺得本網(wǎng)站對您的學習有所幫助,可以手機掃描二維碼進行捐贈