跳到正文

个人记录

【学习笔记】可持久化块状链表

IMIDAZOLE约 3 分钟
原文
文章信息与版本

文章信息

发布
2022年11月17日
收录
2025年12月12日
更新
2026年11月15日
篇幅
约 3 分钟

版本

  1. v1当前

前言:站在巨人的肩膀上……

可持久化块状链表

STL数据结构 rope 就是用可持久化块状链表实现的。

HELP

用法:

首先,要使用 rope,需要加上以下两行:

C++
#include<ext/rope>
using namespace __gnu_cxx;

然后我们可以定义一个字符串类型的 rope,叫做 crope,要这样定义:

C++
crope a;
crope s[10];

crope 支持的操作:

注:从 0 开始

  • a.push_back(x):在末尾添加 x
  • a.insert(k,x):在 k 插入 x
  • a.erase(k,x):从 k 开始删除 x 个
  • a.replace(k,x):将 k 换成 x
  • a.substr(k,x):提取 k 开始 x 个
  • a.at(k):访问第 x 个元素

时间复杂度:O(nn)O(n \sqrt n)。

题目:P1383 高级打字机

难度:蓝题。

双倍经验:P6166 [IOI2012] scrivener

前言:本来应该用主席树打的,可是翻题解的时候发现这么一个好东西,那就学学用用呗。

思路:

我们可以拿一个字符串数组来保存历史版本,每次读入操作,执行操作,保存到第 tottot 个历史版本中。

对于操作 TT,我们可以使用 push_back 或 insert

对于操作 UU ,我们可以直接回退到 tot−ktot-k 的版本

对于操作 QQ,我们可以使用 at 或 substr

然后就水过去了。

时间复杂度:O(nn)O(n \sqrt n)。

CODE:

C++
#include<bits/stdc++.h>
#include<ext/rope>
#define LL long long
using namespace __gnu_cxx;
using namespace std;
const int N = 1e5 + 10;
crope now,last[N]; // 保存现存的串和历史版本
int n,tot,len; 
int read() {
	int x = 0,f = 1;
	char c = getchar();
	while(c < '0' || c > '9') {
		if(c == '-')	f = -1;
		c = getchar();
	}
	while(c >= '0' && c <= '9') {
		x = (x << 1) + (x << 3) + (c ^ 48);
		c = getchar();
	}
	return x * f;
}
int main() {
	n = read();
	for(int i = 1;i <= n;i ++) {
		char c;cin >> c;
		if(c == 'T') {
			char cc;cin >> cc;
			now.insert(len,cc);
			len ++;
			last[++ tot] = now;
		}
		if(c == 'U') {
			int k = read();
			now = last[tot - k];
			last[++ tot] = now;
		}
		if(c == 'Q') {
			int k = read();
			printf("%c\n",now.at(k - 1));
		}
	}
	return 0;
}
原文