BerOS File Suggestion(字符串匹配map)
BerOS File Suggestion(stl-map应用)
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 f1,f2,…,fn. 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".
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 fi — 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 s1,s2,…,sq, one per line. Each sj has length between 1 and 8
characters, inclusive. It contains only lowercase Latin letters, digits and dot characters ('.').
Print q
lines, one per query. The j-th line should contain the response on the j-th query — two values cj and tj
, where
- cjis the number of matched files for the j-th query, tj 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.
4
test
contests
test.
.test
6
ts
.
st.
.test
contes.
st
1 contests
2 .test
1 test.
1 .test
0 -
4 test.
MAP是个好东西
题意:
给你n个字符串,再给你q次查询,问你每一次查询的字符串是n个字符串中多少个字符串的子串,并随机输出其中一个原串
分析:将给出的n个字符串的所有子串全部存起来,长度为1的子串,长度为2....长度为size的子串,再将查询的字符串与所有的子串比对。再开一个map,用来记录该子串所在的原串。
1 #include<cstdio>
2 #include<algorithm>
3 #include<cstring>
4 #include<map>
5 #include<iostream>
6 using namespace std;
7 map<string,int> strr;
8 map<string,string> sstr;
9 int main()
10 {
11 int n;
12 while(~scanf("%d",&n)) {
13 while(n--) {
14 string a;
15 cin>>a;
16 map<string,int> outrepeat;//去重,防止一个字符串中,同样的子串出现不止一次
17 for(int i=0;i<a.size();i++) {
18 for(int j=1;j<=a.size();j++) {
19 string b;
20 b=a.substr(i,j);
21 if(outrepeat[b]==0) {//去重
22 strr[b]++;//该子串在n个原串中出现的次数
23 sstr[b]=a;//记录该子串所属的原串
24 outrepeat[b]=1;
25 }
26 }
27 }
28 }
29 int m;
30 scanf("%d",&m);
31 while(m--) {
32 string c;
33 cin>>c;
34 if(strr[c]>0)
35 cout<<strr[c]<<" "<<sstr[c]<<endl;
36 else
37 cout<<"0 -"<<endl;
38 }
39 }
40 return 0;
41 }