这道题如果不看测试用例的话,可能思路就不明确,但是一看到他给的测试用例,会不自觉地想到map<string , vector< int > >,并且考虑到输出要按升序来, 所以vector可以被set< int >代替。代码如下:
#include <cstdio>
#include <iostream>
#include <set>
#include <map>
#include <string>
using namespace std;
map<string, set<int> > query[10];
int main(){
int n;
scanf("%d",&n);
for (int i=0; i<n; i++){
int id;
scanf("%d",&id);
getchar();
for (int j=1; j<=5; j++){
string str;
if (j==3){
while (cin>>str){
query[j][str].insert(id);
char c=getchar();
if (c=='\n') break;
}
continue;
}
getline(cin,str);
query[j][str].insert(id);
}
}
int m;
scanf("%d",&m);
for (int i=0; i<m; i++){
int temp;
scanf("%d: ",&temp);
string key;
getline(cin,key);
printf("%d: ",temp);
cout<<key<<endl;
if (query[temp][key].size()==0){
printf("Not Found\n");
continue;
}
for (set<int>::iterator it=query[temp][key].begin(); it!=query[temp][key].end(); it++){
printf("%07d\n",*it);
}
}
}
有几点可以学习或者需要注意的地方:
- 读取一个数字以后,要用getchar()把后面的换行读取。
- while (cin>>str)那里的写法值得学习。
- 测试点的最后两组数据的id小于7位数,或者有前导0。所以输出的时候要按照“%07d"格式来,这个有点坑爹了。
本文介绍了一种使用map<string,set<int>>的数据结构来优化查询效率的方法,通过实例讲解了如何读取和处理数据,以及在输出时如何确保ID的正确格式。


被折叠的 条评论
为什么被折叠?



