P1160 队列安排 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
一开始的想法,就是用双向链表模拟一下就完了:
#include <iostream>
using namespace std;
const int N = 1e5 + 10;
int e[N], l[N], r[N], pos[N], idx; //pos存e[i]是第几个插入的
int n, m;
void init()
{
r[0] = 1;
l[1] = 0;
idx = 2;
}
void add_r(int x, int k)
{
pos[x] = idx;
e[idx] = x;
l[idx] = k;
r[idx] = r[k];
l[r[k]] = idx;
r[k] = idx ++;
}
void remove(int k)
{
r[l[k]] = r[k];
l[r[k]] = l[k];
}
int main()
{
cin >> n;
init();
add_r(1, 0);
pos[1] = 2;
for(int i = 2; i <= n; i ++ )
{
int x, k;
cin >> x >> k;
if(k)
add_r(i, pos[x]);
else
add_r(i, l[pos[x]]);
}
// for(int i = r[0]; i != 1; i = r[i])
// {
// cout << e[i] << ' ';
// }
// cout << endl;
cin >> m;
while(m -- )
{
int x;
cin >> x;
for(int i = r[0]; i != 1; i = r[i])//遍历删掉x号
{
if(e[i] == x) remove(i);
}
}
for(int i = r[0]; i != 1; i = r[i]) //遍历输出
{
cout << e[i] << ' ';
}
return 0;
}
但是有两个点t了
优化一下删除的那里
#include <iostream> using namespace std; const int N = 1e5 + 10; int e[N], l[N], r[N], pos[N], idx, st[N]; int n, m; void init() { r[0] = 1; l[1] = 0; idx = 2; } void add_r(int x, int k) { pos[x] = idx; e[idx] = x; l[idx] = k; r[idx] = r[k]; l[r[k]] = idx; r[k] = idx ++; } // void remove(int k) // { // r[l[k]] = r[k]; // l[r[k]] = l[k]; // } int main() { cin >> n; init(); add_r(1, 0); pos[1] = 2; for(int i = 2; i <= n; i ++ ) { int x, k; cin >> x >> k; if(k) add_r(i, pos[x]); else add_r(i, l[pos[x]]); } // for(int i = r[0]; i != 1; i = r[i]) // { // cout << e[i] << ' '; // } // cout << endl; cin >> m; while(m -- ) { int x; cin >> x; st[x] = true; } for(int i = r[0]; i != 1; i = r[i]) //遍历输出 { if(!st[e[i]]) cout << e[i] << ' '; } return 0; }
stl做法:
转自洛谷orina_zju大佬
#include <cstdio> #include <list> using namespace std; using Iter = list<int>::iterator; const int maxN = 1e5 + 10; Iter pos[maxN]; list<int> queList; bool erased[maxN]; int N; void buildQueue() { queList.push_front(1); pos[1] = queList.begin(); for (int i = 2; i <= N; i++) { int k, p; scanf("%d%d", &k, &p); if (p == 0) { pos[i] = queList.insert(pos[k], i); //left } else { auto nextIter = next(pos[k]); pos[i] = queList.insert(nextIter, i); //right } } int M; scanf("%d", &M); for (int x, i = 1; i <= M; i++) { scanf("%d", &x); if (!erased[x]) { queList.erase(pos[x]); } erased[x] = true; } } int main() { scanf("%d", &N); buildQueue(); bool first = true; for (int x: queList) { if (!first) putchar(' '); first = false; printf("%d", x); } putchar('\n'); return 0; }