Description
Polycarp is working on a new operating system called BerOS. He asks you to help with implementation of a file suggestion feature.
There are
n
files on hard drive and their names are
f
1
,
f
2
,
…
,
f
n
. Any file name contains between
1
and
8
characters, inclusive. All file names are unique.
The file suggestion feature handles queries, each represented by a string
s
. For each query
s
it should count number of files containing
s
as a substring (i.e. some continuous segment of characters in a file name equals
s
) and suggest any such file name.
For example, if file names are “read.me”, “hosts”, “ops”, and “beros.18”, and the query is “os”, the number of matched files is
2
(two file names contain “os” as a substring) and suggested file name can be either “hosts” or “beros.18”.
Input
The first line of the input contains integer
n
(
1
≤
n
≤
10000
) — the total number of files.
The following
n
lines contain file names, one per line. The
i
-th line contains
f
i
— the name of the
i
-th file. Each file name contains between
1
and
8
characters, inclusive. File names contain only lowercase Latin letters, digits and dot characters (’.’). Any sequence of valid characters can be a file name (for example, in BerOS “.”, “…” and “…” are valid file names). All file names are unique.
The following line contains integer
q
(
1
≤
q
≤
50000
) — the total number of queries.
The following
q
lines contain queries
s
1
,
s
2
,
…
,
s
q
, one per line. Each
s
j
has length between
1
and
8
characters, inclusive. It contains only lowercase Latin letters, digits and dot characters (’.’).
Output
Print
q
lines, one per query. The
j
-th line should contain the response on the
j
-th query — two values
c
j
and
t
j
, where
c
j
is the number of matched files for the
j
-th query,
t
j
is the name of any file matched by the
j
-th query. If there is no such file, print a single character ‘-’ instead. If there are multiple matched files, print any.
Sample Input
Input
4
test
contests
test.
.test
6
ts
.
st.
.test
contes.
st
Output
1 contests
2 test.
1 test.
1 .test
0 -
4 .test
寻找子串,不能用KMP,因为已知串的长度都不超过8,所以就可以直接找已知串的所有子串存到map里
定义三个map,一个记录这个子串出现的次数,一个用来标记这个子串是否找过,另一个存储这个子串的母串(任意一个)
代码:
#include<iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <map>
#include <cstdlib>
#include <algorithm>
#define ll long long
#define INF 0x3f3f3f
const int MAX=1e5+10;
using namespace std;
map <string,string> ans;
map <string,int> cnt;
map <string,bool> vis;
char a[20];
string str;
int main()
{
int n;
cin>>n;
while(n--)
{
scanf("%s",a);
vis.clear();
int len=strlen(a);
for(int i=0;i<len;i++)
{
str=""; //清空str
for(int j=i;j<len;j++)
{
str+=a[j]; //从串的第一位开始往后找所有子串,再从第二位开始
if(!vis[str]) //这个子串之前未出现过
{
cnt[str]++; //子串出现次数加1
ans[str]=a; //记录母串
vis[str]=true; //表示这个子串已经存在
}
}
}
}
int q;
cin>>q;
while(q--)
{
scanf("%s",a);
if(cnt[a]==0)
cout<<"0 -"<<endl;
else
cout<<cnt[a]<<" "<<ans[a]<<endl;
}
return 0;
}