CSP 考试中学生排队问题的 Vector 动态数组解法
在 CSP 认证或类似的算法竞赛中,处理动态变化的队列是常见考点。相比于固定大小的数组,std::vector 能自动管理内存,非常适合这种人数不确定的场景。
下面是一个典型的实现思路。我们不需要预先分配最大容量,而是根据实际输入动态调整。
#include <iostream>
#include <vector>
using namespace std;
int main() {
// 模拟学生编号
vector<int> students;
int n, m;
// 读取总人数和操作次数
if (!(cin >> n >> m)) return 0;
// 初始化队伍
for (int i = 1; i <= n; ++i) {
students.push_back(i);
}
// 处理操作
while (m--) {
int op, pos;
cin >> op >> pos;
if (op == 1) {
// 插入操作:在第 pos 个位置前插入新学生(假设新学生编号为当前最大值 +1)
// 注意:vector 插入会移动后续元素,复杂度 O(N)
students.insert(students.begin() + pos - 1, students.size() + 1);
} else if (op == 2) {
// 删除操作:移除第 pos 个位置的学生
if (pos >= 1 && pos <= students.size()) {
students.(students.() + pos - );
}
} (op == ) {
(pos >= && pos <= students.()) {
cout << students[pos - ] << endl;
}
}
}
;
}


