跳到正文

个人记录

算法笔记(3)——rope

幻想繁星约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 4 分钟
获赞
2

版本

  1. v1当前

一、简介

rope,顾名思义就是“绳”。

本来是一种可以快速处理 string 类型修改的数据类型,但是因为其可以 O(1)O(1) 复制的原因,导致可以在一些情况作为可持久化数组使用。

二、定义

使用前需要先调用头文件 #include <ext/rope> 和命名空间 using namespace __gnu_cxx;。

定义是符合 STL 格式的,即 rope<T>,其中 T 为存储的数据类型。

例如,rope<int>t 就是定义一个存储 int 类型的 rope 且命名为 tt。

三、使用

rope 支持以下几种操作:

  • push_back(x) 在末尾插入 xx(O(1)O(1))

  • insert(pos,x) 在 pospos 处插入 xx(O(n)O(\sqrt{n}))

  • erase(pos,x) 在 pospos 处删除 xx 个元素(O(n)O(\sqrt{n}))

  • size 返回 rope 的大小(O(1)O(1))

  • replace(pos,x) 将 pospos 处的元素替换成 xx(O(n)O(\sqrt{n}))

  • substr(pos,x) 从 pospos 处开始提取 xx 个元素(O(n+x)O(\sqrt{n}+x))

  • copy(pos,x,s) 从 pospos 处开始复制 xx 个元素到 ss 中(O(n+x)O(\sqrt{n}+x))

  • [x] 或 at(x) 访问第 xx 个元素(O(n)O(\sqrt{n}))

  • = 将一个 rope 复制给另一个 rope(O(1)O(1))

四、复杂度

空间复杂度是 O(n+n)O(n+\sqrt{n}) 的。

时间复杂度见上。

五、例题

P3919 【模板】可持久化线段树 1(可持久化数组)

C++
#include<bits/stdc++.h>
using namespace std;
#include<ext/rope>
using namespace __gnu_cxx;
vector<rope<int> >t(1000006);
int n,m;
int main()
{
	read(n,m);
	for(int i=1;i<=n;i++)
		t[0].push_back(read());
	for(int i=1;i<=m;i++)
	{
		int v,opt,loc;
		read(v,opt,loc);
		t[i]=t[v];
		if(opt==1)
			t[i].replace(loc-1,read());
		else
			write(t[i][loc-1],'\n');
	}
	return 0;
}

P3391 【模板】文艺平衡树

C++
#include<bits/stdc++.h>
#include<ext/rope>
using namespace std;
using namespace __gnu_cxx;
int n,m,l,r;
rope<int>a,b,tmp;
int main()
{
	int len;
	cin>>n>>m;
	for(int i=0;i<n;i++)
	{
		a.push_back(i+1);
		b.push_back(n-i);
	}
	while(m--)
	{
		cin>>l>>r;
		l--;
		r--;
		int x=r-l+1;
		tmp=a.substr(l,r-l+1);
		a=a.substr(0,l)+b.substr(n-r-1,r-l+1)+a.substr(r+1,n-r-1);
		b=b.substr(0,n-r-1)+tmp+b.substr(n-l,l);
	}
	for(int i=0;i<n;i++)
		cout<<a[i]<<' ';
	return 0;
}
原文