6.1 vector的常见用法详解
6.1 vector的常见用法详解
http://codeup.hustoj.com/contest.php?cid=100000596
A Course List for Student (25)

题目释义
现给出各个课程的学生列表,要求输出指定学生的课表。
输入第一行n、k分别表示要输出课表的指定学生个数,k表示课程总数目。
接下来为k个课程的相应信息,第一行为课程编号和此课程的所有学生,下一行为各学生名称。
最后一行为输出课表的n个学生姓名。
输出格式:学生姓名、其课程数目、各课程编号【按照递增顺序输出】
题目解析
因为每个学生的课程数目不定,所以可采用不定长数组vector,创建一个学生vector数组,每个元素存储对应学生的所有课程编号,则到时候输出就非常方便。如果学生姓名能作为vector数组的序号就好了。
所以我们意图将学生姓名转换为int型,此处可参考【字符串hash】的做法,因为学生姓名的格式是确定的(前三位大写字母,第四位数字),所以我们将前三位做26进制转10进制运算,最后直接加上第四位数字,这样就将学生姓名转换为int型,而且我们可以很方便的通过O(1)操作就找到学生姓名对应的vector元素。
代码
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
const int MAX = 26 * 26 * 26 * 10 + 5;
vector<int> stu[MAX];
//前面26进制转换为10进制 题目规定输入的字母一定大写,再加上最后一位
int to_10(char *s) {
int ans = 0, temp;
for (int i = 0; i < 3; i++) {
ans = ans * 26 + (s[i] - 'A');
}
ans = ans * 10 + (s[3] - '0');
return ans;
}
int main() {
int n, k;
int index, num;
char name[5];
while (scanf("%d%d", &n, &k) != EOF) {
while (k--) {
scanf("%d%d", &index, &num);
for (int i = 0; i < num; i++) {
scanf("%s", name);
int t = to_10(name);
stu[t].push_back(index);
}
}
for (int i = 0; i < n; i++) {
scanf("%s", name);
int t = to_10(name);
sort(stu[t].begin(), stu[t].end());
printf("%s %d", name, (int) stu[t].size());
for (vector<int>::iterator it = stu[t].begin(); it != stu[t].end(); it++) {
printf(" %d", *it);
}
printf("\n");
}
}
return 0;
}
B Student List for Course (25)

题目释义
现给出各个学生的课表,要求输出各个课程的学生姓名。
输入第一行n、k分别表示学生个数,k表示课程总数目。
接下来的n行为各学生的信息——学生姓名、其选择课程数目、各课程编号。
各个课程的输出格式:
第一行为课程编号、课程学生总数m
接下来m行为各学生姓名【按照递增顺序给出】
题目解析
与A题思路类似,我们使用vector<string>数组存储各课程的所有学生姓名,我们意图以课程编号作为数组索引。
所以此处更简单,直接是整数hash,不用涉及到字符串hash。
⚠️
-
定义 vector<string> s[SIZE],而不是vector<char *> s[SIZE]【每个存储的是char指针,最后输出的所有值相同】
-
vector<char [5]> s[SIZE]不符合语法
代码
#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main() {
int n, k;
vector<string> course[2505];
string name;
int num, temp;
while (scanf("%d%d", &n, &k) != EOF) {
while (n--) {
cin >> name;
scanf("%d", &num);
for (int i = 0; i < num; i++) {
scanf("%d", &temp);
course[temp].push_back(name);
}
}
for (int i = 1; i <= k; i++) {
printf("%d %lu\n", i, course[i].size());
sort(course[i].begin(), course[i].end());
for (vector<string>::iterator it = course[i].begin(); it != course[i].end(); it++) {
cout << *it << endl;
}
}
}
return 0;
}
本文作者:Joey-Wang
本文链接:https://www.cnblogs.com/joey-wang/p/14541173.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步