正文
洛谷P1160
题目解读
题目让我们做一个双端队列出来,但是这是链表的习题,所以我使用双向链表来做
- 根据题意模拟使用双向链表编队
- 根据题意模拟删除对应节点
思路分析
直接根据题意模拟即可,注意要分清插入的左右位置,还有插入节点时的逻辑顺序,以及删除节点的顺序
AC代码
#include <bits/stdc++.h>
using namespace std;
// #define ONLINE_JUDGE
const int N = 100010;
int n, m;
int k, p;
int x;
struct node{
int id;
int nextid, preid;
} nodes[N];
inline void problem() {
cin >> n;
nodes[1].id = 1;
nodes[1].preid = 0;
nodes[1].nextid = n + 1;
for (int i = 2; i <= n; ++i) {
cin >> k >> p;
nodes[i].id = i;
if (p) {
// 插左边
nodes[i].nextid = nodes[k].nextid;
nodes[i].preid = nodes[k].id;
nodes[nodes[k].nextid].preid = nodes[i].id;
nodes[k].nextid = nodes[i].id;
} else {
// 插右边
nodes[i].nextid = nodes[k].id;
nodes[i].preid = nodes[k].preid;
nodes[nodes[k].preid].nextid = nodes[i].id;
nodes[k].preid = nodes[i].id;
}
}
cin >> m;
while (m--) {
cin >> x;
if (nodes[x].nextid || nodes[x].preid) {
nodes[nodes[x].preid].nextid = nodes[x].nextid;
nodes[nodes[x].nextid].preid = nodes[x].preid;
nodes[x].nextid = 0;
nodes[x].preid = 0;
}
}
int now = nodes[0].nextid;
while (nodes[now].id) {
cout << nodes[now].id;
if (nodes[now].nextid) {
cout << ' ';
} else {
cout << '\n';
}
now = nodes[now].nextid;
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif
problem();
return 0;
}