学了字典树
来个模板题
比较习惯用数组
#include<bits/stdc++.h> ///用字典树求前缀
#include<iostream>
#include<ctype.h>
#include<map>
#include<set>
#include<iomanip>
#include<vector>
using namespace std;
typedef long long ll;
const int N = 1e7+7;
const double eps = 1e-7;
const double pi=3.1415926;
const ll mod = 1e9+7;
int tre[1000010][26]; //分别为可能字符数与字母
int num[1000010]={0};
int pos=1;
void insert(char str[]){ ///建树
int cep=0;
for(int i=0;str[i];i++){
int n=str[i]-'a';
if(tre[cep][n]==0){
tre[cep][n]=pos++; ///建立节点
}
cep=tre[cep][n]; ///建立叶节点
num[cep]++; ///计数
}
}
int find(char str[]){ ///查找
int p=0;
for(int i=0;str[i];i++){
int n=str[i]-'a';
if(tre[p][n]==0){ ///没有ci前缀
return 0;
}
p=tre[p][n];
}
return num[p];
}
int main(){
int a,b,c;
char str[27];
while(gets(str)){
if(!strlen(str)){
break;
}
insert(str);
}
while(gets(str)){
cout<<find(str)<<endl;
}
return 0;
}
也可以用map
不过会慢一些
偷懒
#include<iostream> ///map版本
#include<map>
#include<string.h>
using namespace std;
typedef long long ll;
char ar[102],br[102];
int main(){
int a,b,c;
char str[15];
map<string,int>ma;
while(gets(str)){
int len=strlen(str);
if(len==0){
break;
}
for(int i=len;i;i--){
str[i]='\0';
ma[str]++;
}
}
while(gets(str)){
cout<<ma[str]<<endl;
}
return 0;
}
(参考《算法竞赛-入门到进阶》-罗勇军 郭卫斌著)