PAT甲级1047 Student List for Course (25分)|C++实现

一、题目描述

原题链接
Zhejiang University has 40,000 students and provides 2,500 courses. Now given the registered course list of each student, you are supposed to output the student name lists of all the courses.

Input Specification:

在这里插入图片描述

​​Output Specification:

在这里插入图片描述

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

二、解题思路

比较简单的一道题,我们可以用一个vector<string>的数组表示每门课的学生的姓名,下标即为课程的编号,随后对于这个vector数组中的所有vector进行按字母排序,最后按顺序输出即可。

三、AC代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<cstring>
using namespace std;
bool cmp(string a, string b)
{
    
    return a.compare(b) < 0;}
int main()
{
    
    
  int N, K, course, num;
  string name;
  scanf("%d%d", &N, &K);
  vector<string> v[K+1];
  for(int i=0; i<N; i++)
  {
    
    
    cin >> name;
    scanf("%d", &num);
    for(int j=0; j<num; j++)
    {
    
    
      scanf("%d", &course);
      v[course].push_back(name);
    }
  }
  for(int i=1; i<=K; i++)
  {
    
    
    printf("%d %d\n", i, v[i].size());
    sort(v[i].begin(), v[i].end(), cmp);
    for(int j=0; j<v[i].size(); j++)
      printf("%s\n", v[i][j].c_str());
  }
  return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42393947/article/details/108592215