首页 › 题库 › C/C++编程考级 › C/C++编程六级 › 简答题
简答题 偏难
#7551

学生课表 某大学有 40000 名学生,开了 2500 门课。给定所有课程的选课名单,你的任务是为每一位前来查询的学生打印其选课的课表。 时间限制:2000 内…

学生课表

某大学有 40000 名学生,开了 2500 门课。给定所有课程的选课名单,你的任务是为每一位前来查询的学生打印其选课的课表。

时间限制:2000

内存限制:262144

输入

输入第一行给出 2 个正整数:N(≤ 40000)为查询课表的学生人数;K(≤ 2500)为课程总数。 下面给出每门课的选课名单(课程从 1 到 K 编号),格式为: 课程编号 选课人数 学生姓名1 学生姓名2 ... 其中 选课人数 不超过 200 人。学生姓名由 3 个英文大写字母和 1 位数字组成。 最后一行给出 N 个前来查询的学生姓名。 一行中的数字和姓名都以空格分隔。

输出

对每个前来查询的学生,在一行中输出学生的姓名、选课门数、升序输出的课程编号,其间以 1 个空格分隔。行首尾不得有多余空格。

样例输入

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

样例输出

ZOE1 2 4 5
ANN0 3 1 2 5
BOB5 5 1 2 3 4 5
JOE4 1 2
JAY9 4 1 2 4 5
FRA8 3 2 4 5
DON2 2 4 5
AMY7 1 5
KAT3 3 2 4 5
LOR6 4 1 2 4 5
NON9 0
未登录也能判分,登录后才会记录
答案与解析
正确答案:<pre class="brush:cpp;toolbar:false">#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;unordered_map&gt; #include &lt;algorithm&gt; using namespace std; // 比较函数,用于对课程编号进行升序排序 bool compareCourse(const int&amp; a, const int&amp; b) {     return a &lt; b; } int main() {     int N, K;     cin &gt;&gt; N &gt;&gt; K;     // 使用哈希表存储每门课程的选课学生姓名     unordered_map&lt;int, vector&lt;string&gt;&gt; courseToStudents;     // 读取每门课程的选课名单     for (int i = 0; i &lt; K; ++i) {         int courseId, numStudents;         cin &gt;&gt; courseId &gt;&gt; numStudents;         vector&lt;string&gt; students;         for (int j = 0; j &lt; numStudents; ++j) {             string studentName;             cin &gt;&gt; studentName;             students.push_back(studentName);             courseToStudents[courseId].push_back(studentName);         }     }     // 读取前来查询的学生姓名     vector&lt;string&gt; queryStudents;     for (int i = 0; i &lt; N; ++(i)) {         string studentName;         cin &gt;&gt; studentName;         queryStudents.push_back(studentName);     }     // 为每个查询的学生打印课表     for (const string&amp; studentName : queryStudents) {         vector&lt;int&gt; selectedCourses;         // 遍历所有课程,查找该学生所选的课程         for (const auto&amp; coursePair : courseToStudents) {             const vector&lt;string&gt;&amp; students = coursePair.second;             if (find(students.begin(), students.end(), studentName)!= students.end()) {                 selectedCourses.push_back(coursePair.first);             }         }         // 对所选课程进行升序排序         sort(selectedCourses.begin(), selectedCourses.end(), compareCourse);         // 输出学生课表信息         cout &lt;&lt; studentName &lt;&lt; " " &lt;&lt; selectedCourses.size() &lt;&lt; " ";         for (int courseId : selectedCourses) {             cout &lt;&lt; courseId &lt;&lt; " ";         }         cout &lt;&lt; endl;     }     return 0; }</pre>
这道题暂未补解析。