0
点赞
收藏
分享

微信扫一扫

PAT_甲级_1047 Student List for Course (25分) (C++)【字符串存储/排序】


 

1,题目描述

PAT_甲级_1047 Student List for Course (25分)  (C++)【字符串存储/排序】_1047

Sample Input:

10 5
ZOE1 2 4 5
ANN0 3 5 2 1
BOB5 5 3 4 2 1 5
JOE4 1 2
JAY9 4 1 2 5 4
FRA8 3 4 2 5
DON2 2 4 5
AMY7 1 5
KAT3 3 5 4 2
LOR6 4 2 4 1 5

 

Sample Output:

1 4
ANN0
BOB5
JAY9
LOR6
2 7
ANN0
BOB5
FRA8
JAY9
JOE4
KAT3
LOR6
3 1
BOB5
4 7
BOB5
DON2
FRA8
JAY9
KAT3
LOR6
ZOE1
5 9
AMY7
ANN0
BOB5
DON2
FRA8
JAY9
KAT3
LOR6
ZOE1

题目大意

给出每个学生选的课程,要求输出每门课程对应的选课学生姓名。

 

2,思路

比较简单,可以直接看代码,

若想要节省空间,可以考虑将名字转换为编号进行存储(方法二)。在排序时需注意二维字符数组存储字符串,比较大小时需要用strcmp(stringcompare);

 

3,代码

方法一:map> data 

暴力解法(无视内存。。。)

#include<iostream>
#include<vector>
#include<string.h>
#include<map>
#include<math.h>
#include<algorithm>
#include<climits>
using namespace std;

bool cmp1(string a, string b){
return a < b;
}

int main(){
//#ifdef ONLINE_JUDGE
//#else
// freopen("1.txt", "r", stdin);
//#endif

int N, K;
cin>>N>>K;

map< int,vector<string> > data;
string name;
name.resize(4);
int num, course;
for(int i = 0; i < N; i++){
scanf("%s %d", &name[0], &num);
for(int j = 0; j < num; j++){
scanf("%d", &course);
data[course].push_back(name);
}
}

for(int i = 1; i <= K; i++){
sort(data[i].begin(), data[i].end(), cmp1);
printf("%d %d\n", i, data[i].size());
for(int j = 0; j < data[i].size(); j ++){
printf("%s\n", data[i][j].c_str());
}
}

return 0;
}

方法二:编号代替字符串(节省空间)

#include<iostream>
#include<vector>
#include<string.h>
#include<algorithm>
using namespace std;

char name[40001][5];
vector<int> course[2501]; //每门课程对应一个数组(vector容器表示)

bool cmp1(int a, int b){
//return name[a] < name[b];//错误 此语句是在比较地址 不是字符串
return strcmp(name[a], name[b]) < 0; //字符串比较string compare
}

int main(){
//#ifdef ONLINE_JUDGE
//#else
// freopen("1.txt", "r", stdin);
//#endif

int N, K;
cin>>N>>K;


int num, cour;
for(int i = 0; i < N; i++){
scanf("%s %d", name[i], &num);
for(int j = 0; j < num; j++){
scanf("%d", &cour);
course[cour].push_back(i);
}
}

for(int i = 1; i <= K; i++){
sort(course[i].begin(), course[i].end(), cmp1);
printf("%d %d\n", i, course[i].size());
for(int j = 0; j < course[i].size(); j++){
printf("%s\n", name[course[i][j]]);
}
}

return 0;
}

 

4,测试结果

方法一: 

赤裸裸的暴力解法。。。(居然也可以过。)

PAT_甲级_1047 Student List for Course (25分)  (C++)【字符串存储/排序】_PAT_02

方法二:

差距明显!!!

PAT_甲级_1047 Student List for Course (25分)  (C++)【字符串存储/排序】_C++_03

 

举报

相关推荐

0 条评论