解法一:Map+Set

MapSet 存储每个学生的选课信息, STLSet 是有序的。

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. // (name, set<course index>)
  4. map<string, set<int>> stuMap;
  5. int main() {
  6. ios::sync_with_stdio(false);
  7. cin.tie(0);
  8. int N, K;
  9. cin >> N >> K;
  10. int index, num;
  11. string stuName;
  12. for (int i = 0; i < K; ++i) {
  13. cin >> index >> num;
  14. for (int j = 0; j < num; ++j) {
  15. cin >> stuName;
  16. auto res = stuMap.find(stuName);
  17. if (res == stuMap.end()) {
  18. stuMap.emplace(stuName, set<int>{index});
  19. } else {
  20. res->second.insert(index);
  21. }
  22. }
  23. }
  24. for (int i = 0; i < N; ++i) {
  25. cin >> stuName;
  26. cout << stuName << " ";
  27. auto res = stuMap.find(stuName);
  28. if (res == stuMap.end()) {
  29. cout << "0\n";
  30. } else {
  31. cout << res->second.size();
  32. for (auto e:res->second) {
  33. cout << " " << e;
  34. }
  35. cout << '\n';
  36. }
  37. }
  38. }