Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
注意:本题只有一组测试数据,处理到文件结束.
banana band bee absolute acm ba b band abc
2 3 1 0
题意很好懂 因为这道题数据很弱所以map也能做
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<map>
#include<vector>
#include<queue>
#define LL long long
const int INF=1e7+5;
using namespace std;
map<string,int>m;
string s;
char a[20];
int main()
{
while(gets(a)&&a[0]!='\0')
{
int k=strlen(a);
s="\0";
for(int i=0;i<k;i++)
{
s+=a[i];
m[s]++;
}
}
while(gets(a))
{
printf("%d\n",m[a]);
}
}
我感觉正确做法应该是字典树
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<map>
#include<vector>
#include<queue>
#define LL long long
const int INF=1e7+5;
using namespace std;
int a[550000][26];
int f[550000];
char s[20];
char b[1000];
int cnt=0;
void B(char s[])
{
int t=strlen(s);
int x=0;
for(int i=0;i<t;i++)
{
int y=s[i]-'a';
if(!a[x][y]) a[x][y]=++cnt;
x=a[x][y];
f[x]++;
}
}
int S(char s[])
{
int t=strlen(s);
int x=0;
for(int i=0;i<t;i++)
{
int y=s[i]-'a';
if(!a[x][y]) return 0;
else x=a[x][y];
}
return f[x];
}
int main()
{
memset(a,0,sizeof(a));
memset(f,0,sizeof(f));
while(gets(s))
{
if(s[0]=='\0')
break;
B(s);
}
while(gets(b))
{
printf("%d\n",S(b));
}
}