我是用链表做的这道题,用vector students保存每个学生的编号,以及左边和右边的同学的编号;用most_left记录开始位置。当左边或右边没有同学时值为-1。可是在实际运行时most_left的右边总会是-1,不知道是怎么回事
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Student {
int id;
int left = -1;
int right = -1;
bool hidden = false;
};
int main() {
int n;
cin >> n;
vector<Student> students;
Student first;
first.id = 1;
students.push_back(first);
Student most_left = students[0];
for (int i = 0; i < n-1; ++i) {
int k, p;
scanf("%d%d", &k, &p);
Student to_add;
to_add.id = i+2;
if (k == most_left.id && p == 0) {
most_left = to_add;
}
if (p == 0) {
to_add.right = k;
to_add.left = students[k-1].left;
students[students[k-1].left-1].right = to_add.id;
students[k-1].left = to_add.id;
} else if (p == 1) {
to_add.left = k;
to_add.right = students[k-1].right;
students[students[k-1].right-1].left = to_add.id;
students[k-1].right = to_add.id;
}
students.push_back(to_add);
//cout << "Pushing back " << to_add.left << " " << to_add.id << " " << to_add.right << endl;
}
int M;
cin >> M;
for (int j = 0; j < M; ++j) {
int id_to_remove;
cin >> id_to_remove;
students[id_to_remove-1].hidden = true;
}
while (most_left.right != -1) {
if (!most_left.hidden) cout << most_left.id << " ";
most_left = students[most_left.right-1];
}
cout << most_left.id << " " << most_left.right << endl;
}