【2022.11.12】1. 链表 --- 作业

正文

洛谷P1160

P1160 队列安排

题目解读

题目让我们做一个双端队列出来,但是这是链表的习题,所以我使用双向链表来做

  1. 根据题意模拟使用双向链表编队
  2. 根据题意模拟删除对应节点

思路分析

直接根据题意模拟即可,注意要分清插入的左右位置,还有插入节点时的逻辑顺序,以及删除节点的顺序

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;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值