算法提高 盾神与条状项链 双向链表

       思路:用双向链表,next[x] = y表示颜色为x的珠子的下一个珠子的颜色是y,pre[x] = y表示表示颜色为x的珠子的上一个珠子的颜色是y。时间复杂度是O(n + m)

#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <utility>
#include <string>
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
#pragma comment(linker, "/STACK:1024000000,1024000000") 
#define eps 1e-10
#define inf 0x3f3f3f3f
#define PI pair<int, int> 
typedef long long LL;
const int maxn = 1e5 + 5;
int next[maxn], pre[maxn];
int n, m, head, len;
//双向链表 

void Insert(int key, int pos1, int pos2) {
	++len;
	next[key] = pos2;
	next[pos1] = key;
	pre[key] = pos1;
	pre[pos2] = key;
}
void init(int n) {
	head = 0; next[head] = 0; pre[head] = 0;
	int x, prev = 0;
	for(int i = 0; i < n; ++i) {
		scanf("%d", &x);
		Insert(x, prev, next[prev]);
		prev = x;
	}
}
void Delete(int key, int pos1, int pos2) {
	--len;
	next[pos1] = pos2;
	pre[pos2] = pos1;
}
void print() {
	printf("%d\n", len); 
	int nex = next[head];
	while(nex) {
		printf("%d ", nex);
		nex = next[nex];
	}
	printf("\n");
}
int main() {
	while(scanf("%d%d", &n, &m) == 2) {
		len = 0;
		init(n);
		char op[5];
		int x, y;
		for(int i = 0; i < m; ++i) {
			scanf("%s", op);
			if(op[0] == 'A') {
				scanf("%d%d", &x, &y);
				Insert(y, pre[x], x);
			}
			else {
				scanf("%d", &x);
				Delete(x, pre[x], next[x]);
			}
		}
		print();
	}
	return 0;
}

如有不当之处欢迎指出!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值