题目链接
题目分析
解题思路
思路(一):
用map<string, set<int> >
边输入变保存
把name
用字符串hash转为int
,进而用map<int, set<int> >
,同上
思路(二):
把string
用字符串hash转为int
,作为数组set<int> cour[]
的下标
**tips:**此处改用vector()
+ sort()
也不会超时
注:需要把数组大小设为500000以上,作为全局变量放在main()外
map版本
/**************************
*@Author: 3stone
*@ACM: PAT-A1039
*@Time: 17/3/4
*@IDE: VS 2017
***************************/
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<map>
#include<set>
#include<string>
using namespace std;
map<string, set<int> > list;
int main() {
int N, K, subID, num;
char temp[5];
string name;
scanf("%d %d", &N, &K);
for(int i = 1; i <= K; i++) {
scanf("%d%d", &subID, &num);
for(int j = 0; j < num; j++) {
scanf("%s", temp);
name = temp;
list[name].insert(subID);
}
}
for(int i = 0; i < N; i++) { //查询
scanf("%s", temp);
name = temp;
printf("%s %d", temp, list[name].size());
for(set<int>::iterator it = list[name].begin(); it != list[name].end(); it++) {
printf(" %d", *it);
}
printf("\n");
}
system("pasue");
return 0;
}
字符串hash 版本
/**************************
*@Author: 3stone
*@ACM: PAT-A1039
*@Time: 17/3/4
*@IDE: VS2017
***************************/
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
const int N = 40010;
const int M = 26 * 26 * 26 * 10 + 1;
vector<int> cs[M];
int getID(char name[]){//字符串转数字ID
int id = 0;
for(int i = 0; i < 3; i++){//前3位按26进制累加,最后1位数字直接加上去
id = id * 26 + (name[i] - 'A');
}
id = id * 10 + (name[3] - '0');
return id;
}
int main(){
int n, k;
while(scanf("%d%d", &n, &k) != EOF){
char name[5];
for(int i = 0; i < k; i++){//输入数据
int x, course;
scanf("%d%d", &course, &x);
for(int j = 0; j < x; j++){
scanf("%s", name);
int id = getID(name);
cs[id].push_back(course);
}
}
//输入选课人员
for(int i = 0; i < n; i++){
char name[5];
scanf("%s", name);
int id = getID(name);
sort(cs[id].begin(), cs[id].end());
printf("%s %d", name, cs[id].size());
for(int j = 0; j < cs[id].size(); j++)
printf(" %d", cs[id][j]);
printf("\n");
}//for-i
} //while
return 0;
}