字典树裸题,在Node里用num记录该Node到root表示的前缀出现的次数,每插入一次就+1。
#include <iostream>
#include <algorithm>
#include <string>
#include <stdio.h>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iomanip>
#include <queue>
#include <map>
#define N 500000
using namespace std;
const int INF = 0x3f3f3f3f;
char s[15];
struct Node{
Node* ch[26];
int num;
}a[N],*root;
int p = 0;
Node* newNode(){
p++;
memset(a[p].ch,0,sizeof(a[p].ch));
a[p].num = 0;
return &a[p];
}
void insert(char s[]){
Node* cur = root;
cur->num++;
int i = 0;
while (*s != '\0')
{
int x = *s - 'a';
if(cur->ch[x] == NULL){
cur->ch[x] = newNode();
}
cur = cur->ch[x];
cur->num++;
s++;
}
}
int find(char s[]){
Node* cur = root;
while (*s != '\0')
{
int x = *s - 'a';
if(cur->ch[x] == NULL){
return 0;
}
cur = cur->ch[x];
s++;
}
return cur->num;
}
int main(){
root = newNode();
while(gets(s) && s[0] != '\0')
{
insert(s);
}
while (scanf("%s",s)!=EOF)
{
printf("%d\n",find(s));
}
return 0;
}