字典树解法
#include<bits/stdc++.h>
using namespace std;
struct Trie //字典树模板
{
int word[400020][26];
int ex[4000020];
int sz;
Trie()
{
sz=1;
memset(word,0,sizeof(word));
memset(ex,0,sizeof(ex));
}
void insert(char *s) //插入
{
int u=0;
int c;
int len=strlen(s);
for(int i=0;i<len;i++)
{
c=s[i]-'a';
if(!word[u][c])
word[u][c]=sz++;
u=word[u][c];
ex[u]++;
}
}
int search(char *s) //查询
{
int u=0;
int c;
int len=strlen(s);
for(int i=0;i<len;i++)
{
c=s[i]-'a';
if(word[u][c])
u=word[u][c];
else
return 0;
}
return ex[u];
}
}w;
int main()
{
char s[20];
while(gets(s)&&*s)
w.insert(s);
while(gets(s))
printf("%d\n",w.search(s));
return 0;
}
map解法
#include<bits/stdc++.h>
using namespace std;
map<string,int>m;
int main()
{
string s;
char c;
while(1)
{
scanf("%c",&c);
if(c=='\n')
{
scanf("%c",&c);
s="";
}
if(c=='\n')
break;
s+=c;
m[s]++;
}
while(cin>>s)
printf("%d\n",m[s]);
return 0;
}