Files
exercises/luogu_P1160_biodir_linked_list.cpp
T
2026-09-09 13:38:11 +08:00

86 lines
1.8 KiB
C++

#include <cassert>
#include <iostream>
#include <vector>
using namespace std;
class LinkedList {
public:
struct Node {
int previous = -1, next = -1;
};
vector<Node> nodes;
int get_adjacent(int idx, bool next) const {
if (next) { return nodes[idx].next; }
return nodes[idx].previous;
}
void add(int l, int r) {
if (l > -1) { nodes[l].next = nodes.size(); }
if (r > -1) { nodes[r].previous = nodes.size(); }
nodes.push_back({.previous = l, .next = r});
}
void remove(int idx) {
if (nodes[idx].previous > -1) {
nodes[nodes[idx].previous].next = nodes[idx].next;
}
if (nodes[idx].next > -1) {
nodes[nodes[idx].next].previous = nodes[idx].previous;
}
nodes[idx] = {-2, -2};
}
void print() {
int start_idx = -1;
for (int i = 0; i < nodes.size(); i++) {
if (nodes[i].previous == -1) {
start_idx = i;
break;
}
}
for (int i = start_idx; i != -1; i = nodes[i].next) {
cout << i + 1 << " ";
}
cout << endl;
}
};
LinkedList l;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
int to_be_operated;
bool is_next;
cin >> n;
l.add(-1, -1);
for (int _ = 0; _ < n - 1; _++) {
cin >> to_be_operated >> is_next;
to_be_operated--;
int adj = l.get_adjacent(to_be_operated, is_next);
if (is_next) {
l.add(to_be_operated, adj);
} else {
l.add(adj, to_be_operated);
}
}
cin >> n;
for (int _ = 0; _ < n; _++) {
cin >> to_be_operated;
l.remove(to_be_operated - 1);
}
l.print();
return 0;
}