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:
Each input file contains one test case. For each case, the first line contains 2numbers: N (≤40,000), the total number of students, and K (≤2,500), the total number of courses. Then N lines follow, each contains a student's name (3 capital English letters plus a one-digit number), a positive number C (≤20) which is the number of courses that this student has registered, and then followed by C course numbers. For the sake of simplicity, the courses are numbered from 1 to K.
Output Specification:
For each test case, print the student name lists of all the courses in increasing order of the course numbers. For each course, first print in one line the course number and the number of registered students, separated by a space. Then output the students' names in alphabetical order. Each name occupies a line.
思路:该题和1039题目类似,思路也类似,题目给了1000ms,但是我第一反应还是用哈希表,使用map数据结构,用课程号作为哈希的key值(因为是按照课程号来进行输出),创建一个学生类,里面使用vector<string>类型的数据结构作为value值(方便存储学生姓名 ,数组一个下面对应一个学生姓名),学生姓名输入以后进行升序排序(注意参数,是对Student里的vector进行排序,而排序准则是string类的升序排序,所以仿函数里面的形参是string类,而sort一般是对vector排序,需要分清排序对象和排序准则)
代码实现:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
class Student
{
public:
vector<string>name;
};
bool Mycompare(string& s1, string& s2)
{
return s1 < s2;
}
int main()
{
int N, K, i, j, cnt, ID;
map<int, Student>m;
scanf("%d%d", &N, &K);
for (i = 0;i < N;i++)
{
char name[10] = { '\0' };
scanf("%s %d", name, &cnt);
//cin >> name >> cnt;
for (j = 0;j < cnt;j++)
{
scanf("%d", &ID);
//cin >> ID;
m[ID].name.push_back(name);
}
}
for (i = 1;i <= K;i++)
{
sort(m[i].name.begin(), m[i].name.end(), Mycompare);
printf("%d %d\n", i, m[i].name.size());
//cout << i << " " << m[i].name.size() << endl;
for (j = 0;j < m[i].name.size();j++)
{
printf("%s\n", m[i].name[j].c_str());
//cout << m[i].name[j] << endl;
}
}
return 0;
}