stl学习之rope

简介

rope是本人在极度不想敲平衡树的情况下从朋友偶然听说的,了解之后用寥寥数行便秒杀了那道平衡树的题。笔者遂深感其强大与低调,故作笔记以纪之。

头文件与定义

#include<bits/stdc++.h>
#include<ext/rope>
using namespace std;
using namespace __gnu_cxx;
rope<char> test;

一些函数

   test.push_back(48);	
   test.push_back(48);
   test.insert(1,66);
   test.insert(3,67);//在某处插入某值
   test.erase(pos,len)//从某处开始删除len个值
   test.at(pos)//访问pos处的值
   test.substr(pos,x)//将原容器从pos开始的x个元素提取并返回一个新的rope,可像string一样直接相加
       

核心用法——可持久化

这个操作的存在使得它可以O(1)复制自己,巨nb

rope<char>*a,*b;
a=new rope<char>;
b=new rope<char>(*a);

例题

The first line will contain 0 < N ≤ 105,0 < Q < 5*105, the number of elements in TODO-list and number of queries.
Then a line with N numbers follows. Each number 0 ≤ Ak ≤ 109 means kth number in her TODO-list.Afterward, Q lines follow, each beginning with number 1 ≤ a ≤ 3
1 k x means that you will insert number x to position k
2 k means that you will erase number from position k
3 k means that you will print number from position k

image

代码

本人的提交记录貌似查看不了代码。本题代码来自队友zzh的博客,感谢他

#include <bits/stdc++.h>
#include <ext/rope>
using namespace std;
using namespace __gnu_cxx;
rope<int> r;
int n, m, a;
int op, k, x;

void read(int &x){
	x = 0;
	char c = getchar();
	while(c > '9' || c < '0') c = getchar();
	while(c <= '9' && c >= '0'){
		x = 10 * x + c - '0';
		c = getchar();
	}
	return;
}

int main(){
	read(n),read(m);
	for(int i = 0; i < n; i ++){
		read(a);
		r.push_back(a);
	}
	while(m --){
		read(op), read(k);
		if(op == 1){
			read(x);
			r.insert(k - 1, x);
		}
		else if(op == 2){
			r.erase(k - 1, 1);
		}
		else if(op == 3){
			printf("%d\n", r[k - 1]);
		}
	}
}
posted @ 2023-01-04 00:15  wxk123  阅读(266)  评论(0编辑  收藏  举报