map巧过
#include <stdio.h>
#include <string.h>
#include <map>
#include <string>
using namespace std;
map<string,int>m1;
int main()
{
char z[10];
while(gets(z))
{
if(strlen(z)==0)
break;
for(int i=strlen(z);i>0;i--)
{
z[i]='\0';
m1[z]++;
}
}
while(gets(z))
{
printf("%d\n",m1[z]);
}
return 0;
}
经典前缀树
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
struct node
{
int Count;///以此节点为前缀的单词数
node *next[26];///26叉树
node() ///初始化数据
{
for (int i=0;i<26;i++)
next[i]=NULL;
Count=0;
}
};
node *p,*root=new node();
void Insert(char *s)///插入新单词,即建立字典树
{
int i,k;
p=root;
for (i=0; s[i]!='\0'; i++)
{
k=s[i]-'a';
if (p->next[k]==NULL)
p->next[k]=new node();
///判断是不是新节点,如果是分配创建一个新节点来存贮 ,
///即root的next域对应的k位置是否为空
p=p->next[k];///向前走一步
p->Count++; ///以此位置为前缀的数量+1
}
}
int Search(char *s)
{
int i,k;
p=root;
for (i=0; s[i]!='\0'; i++)
{
k=s[i]-'a';
if (p->next[k]==NULL)///一旦查找不到,立即跳出
return 0;
p=p->next[k];
}
return p->Count;
}
int main()
{
char s[11];
while (gets(s))
{
int len=strlen(s);
if (len==0)
break;
Insert(s);
}
while (gets(s))
{
printf("%d\n",Search(s));
}
return 0;
}
第一个字典树(G++内存超限),第二个map(红黑树),对于此类问题,字典树效率优势明显