Bing wants to showcase its clear superiority over Alphabet’s lesser known search engine in the great bing-it challenge of 2016. In order to do this, they have pulled out all the stops and decided to hire the very best of the best of Norwegian engineers to do the work for them. Bing knows that performance is the name of the game when it comes to the world wide web, and because of this they want to make their typeahead is as performant as possible. Your task is to analyze the stream of searches coming in, and let everyone know how many of these searches began with the letters currently in the search bar.
Input
Each test case begins with a line with a single integer N. The following N lines each contain one word using only the characters a–z.
Output
For each word, output an integer representing how many of the previous words began with or were equal to that word.
Limits
1≤N≤1000001≤N≤100000
Each word has between 11 and 3232 characters.
Sample Input 1 Sample Output 1
10
histories
adventure
history
his
ad
hi
advent
mouse
cat
his
0
0
0
2
1
3
1
0
0
3
题意:给出一个数n,接下来依次输入n个字符串(只由a-z组成),问当前输入的串在前面的串有多少次是作为前缀子串的,两个串相同也算
就是这么一个题,和上次那次的训练赛中的D题类似,然后我卡住了。。。
分析:首先得抓住关键,后面的串可能在前面已经出现过,故记录当前串在前面作为子串的次数,从后往前搜,搜到相同的就停止了,这样节约时间不少,3200ms左右
几乎就是暴力的AC代码:
#include<cstdio>
#include<cstring>
#include<map>
#include<string>
#include<algorithm>
using namespace std;
map<string,int>mp;
struct Node
{
int len,cnt;
char a[33];
}str[100005];
int main()
{
int n;
while(~scanf("%d",&n))
{
for(int i=0;i<n;i++)
{
scanf("%s",str[i].a);
str[i].len=strlen(str[i].a);
int cnt=0;
for(int j=i-1;j>=0;j--)
{
int k=str[j].len;
if(k>=str[i].len)
{
int flag=1;
if(strcmp(str[i].a,str[j].a)==0)
{
cnt+=str[j].cnt+1;
break;
}
for(int m=0;m<str[i].len;m++)
{
if(str[i].a[m]!=str[j].a[m])
{flag=0;
break;
}
}
if(flag)
cnt++;
}
}
printf("%d\n",cnt);
str[i].cnt=cnt;
}
}
return 0;
}
看看学长的map:用map记录了所有当前串的前缀子串已经出现的个数,然后直接输出。。
map的 键->值 关系,用的妙。。
#include<cstdio>
#include<cstring>
#include<map>
#include<string>
#include<algorithm>
using namespace std;
map<string,int>mp;
int main()
{
int n;
char str[33];
while(~scanf("%d",&n))
{
for(int i=0;i<n;i++)
{
scanf("%s",str);
for(int j=0;str[j];j++)
{
char ch=str[j];
str[j]='\0';
mp[string(str)]++;///除输入字符串以外的所有前缀
str[j]=ch;
}
printf("%d\n",mp[str]);
mp[str]++;///该字符串的前缀
}
}
return 0;
}