1. 程式人生 > >Rope大法(可持久化平衡樹)

Rope大法(可持久化平衡樹)

2008年OI集訓論文上有介紹<對塊狀連結串列的一點研究>,其主要是結合了連結串列和陣列各自的優點,連結串列中的節點指向每個資料

塊,即陣列,並且記錄資料的個數,然後分塊查詢和插入。在g++標頭檔案中,<ext/rope>中有成型的塊狀連結串列,在using namespace 

__gnu_cxx;空間中,其操作十分方便。

  基本操作:

rope test;

test.push_back(x);//在末尾新增x

test.insert(pos,x);//在pos插入x  

test.erase(pos,x);//從pos開始刪除x個

test.copy(pos,len,x);//從pos開始到pos+len為止用x代替

test.replace(pos,x);//從pos開始換成x

test.substr(pos,x);//提取pos開始x個

test.at(x)/[x];//訪問第x個元素

其演算法複雜度n*(n^0.5),可以在很短的時間內實現快速的插入、刪除和查詢字串,是一個很厲害的神器!

測試程式碼:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cctype>
#include <ext/rope>
#include <algorithm>
using namespace std;
using __gnu_cxx::crope;

const int maxn = 10010;
char op[maxn];
crope text;

int main(){
    text.clear();
    scanf("%s",op);
    int l = strlen(op);
    for(int i = 0; i < l; i++)
        text += op[i];
    cout<<text<<endl;

    cout<<"test.push_back(x);//在末尾新增x"<<endl;
    text.push_back('a');
    cout<<text<<endl;
    /*
    text.push_back("bbb");
    cout<<text<<endl;//編譯錯誤
    */

    cout<<"test.insert(pos,x);//在pos插入x"<<endl;
    text.insert(1,'b');
    cout<<text<<endl;
    text.insert(2,"aaa");
    cout<<text<<endl<<endl;

    cout<<"test.erase(pos,x);//從pos開始刪除x個"<<endl;
    text.erase(1,3);
    cout<<text<<endl<<endl;

    cout<<"test.copy(pos,len,x);//從pos開始到pos+len為止用x代替"<<endl;
    text.copy(1,5,op);
    cout<<text<<endl<<endl;

    cout<<"test.replace(pos,x);//從pos開始換成x"<<endl;
    text.replace(1,'c');
    cout<<text<<endl;
    text.replace(1,"ccc");
    cout<<text<<endl<<endl<<endl;

    cout<<"test.substr(pos,x);//提取pos開始x個"<<endl;
    //text = text.substr(2);這樣預設為提取一個
    cout<<text.substr(2)<<endl;
    cout<<text.substr(2,3)<<endl<<endl;

    cout<<"test.at(x)/[x];//訪問第x個元素"<<endl;
    cout<<text.at(4)<<endl<<endl;
}