题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805447855292416
知识点:stl的熟练使用
方法1: 运用hash的思想
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#include <map>
using namespace std;
#define inf 0x3f3f3f3f
// 防止超时,使用hash
int getid(char *name)
{
int id = 0;
for (int i = 0; i < 3; i++)
{
id = 26 * id + (name[i] - 'A');
}
id = id * 10 + (name[3] - '0');
return id;
}
const int maxn = 26 * 26 * 26 * 10 + 10;
vector<int> v[maxn]; // 表示二维向量
int main(int argc, const char **argv)
{
std::ios::sync_with_stdio(false);
std::cin.tie(0), cout.tie(0);
int n, k, no, num, id = 0;
char name[5];
scanf("%d %d", &n, &k);
for (int i = 0; i < k; i++)
{
scanf("%d %d", &no, &num);
for (int j = 0; j < num; j++)
{
scanf("%s", name);
id = getid(name);
v[id].push_back(no);
}
}
for (int i = 0; i < id; i++)
{
scanf("%s", name);
id = getid(name);
sort(v[id].begin(), v[id].end());
printf("%s %lu", name, v[id].size());
for (int j = 0; j < v[id].size(); j++)
{
printf(" %d", v[id][j]);
}
printf("\n");
}
return 0;
}
方法2:运用map求解
/ 方法2: 使用map求解
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#include <map>
using namespace std;
#define inf 0x3f3f3f3f
int main(int argc, const char **argv)
{
// std::ios::sync_with_stdio(false);
// std::cin.tie(0), cout.tie(0);
map<string, vector<int>> mp1;
map<vector<int>, string> mp2;
int n, k; // n表示学生的数量,k表示课程的总量
int courseid, num; // 课程索引
cin >> n >> k;
while (k--)
{
cin >> courseid >> num;
for (int i = 0; i < num; i++)
{
string name;
cin >> name;
mp1[name].push_back(courseid);
}
}
for (int i = 0; i < n; i++)
{
string queryname;
cin >> queryname;
cout << queryname << " " << mp1[queryname].size();
sort(mp1[queryname].begin(), mp1[queryname].end());
for (int i = 0; i < mp1[queryname].size(); i++)
{
cout << " " << mp1[queryname][i];
}
cout << endl;
}
return 0;
}