POJ 2887 块状链表

块状链表练手POJ 2887

  • 查询且需要插入

  • 第一个字符串长度不超过 1000000

    分成 $\sqrt(1000000) = 1000$个块


  1. 忘记初始化,
  2. 注意插入的位置,和题目要求的位置
  3. 每次记得维护插入或者删除后 接触块 的大小防止退化
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
//#include <bits/stdc++.h>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <string>
#include <stdio.h>
using namespace std;

const int maxn = 1e3+10;
const int maxn_all = 1e6+10;

struct node {
int next,size;
char a[maxn];
}b[maxn<<2];

int n,cnt,belong[maxn<<2];
char s[10],ss[maxn_all];

void init() {
for (int i=1; i<(maxn<<2); ++i)
belong[i] = i;
cnt = 1;
b[1].size = 0;
b[1].next = -1;
}

int addi() {
cnt++;
return belong[cnt];
}

void dele(int x) {
belong[cnt] = x;
cnt--;
}

void add(int x,int y,int len,char c[]) {
if (y != -1) {
b[y].next = b[x].next;
b[y].size = len;
memcpy(b[y].a,c,len);
}
b[x].next = y;
}

void merge(int x,int y) {
memcpy(b[x].a+b[x].size,b[y].a,b[y].size);
b[x].size += b[y].size;
b[x].next = b[y].next;
dele(y);
}

void split(int k,int pos) {
if (k==-1 || pos==b[k].size) return;
add(k,addi(),b[k].size-pos,b[k].a+pos);
b[k].size = pos;
}

int pos(int &x) {
int now = 1;
while (now!=-1 && x>b[now].size) {
x -= b[now].size;
now = b[now].next;
}
return now;
}

void insert(int p,int len,char c[]) {
int now = pos(p);
split(now,p);
int tot=0,nb,st=now;
while (tot+maxn <= len) {
nb = addi();
add(now,nb,maxn,c+tot);
tot += maxn;
now = nb;
}
if (len-tot) {
nb = addi();
add(now,nb,len-tot,c+tot);
}
if (b[now].size+b[nb].size<maxn && nb!=-1) {
merge(now,nb);
nb = b[now].next;
}
int to = b[st].next;
if (b[st].size+b[to].size<maxn && to!=-1)
merge(st,to);
}

void get(int p,int len) {
int k = pos(p);
int tot = b[k].size - p;
if (len < tot) tot = len;
memcpy(ss,b[k].a+p,tot);
int now = b[k].next;

while (now!=-1 && len>=tot+b[now].size) {
memcpy(ss+tot,b[now].a,b[now].size);
tot += b[now].size;
now = b[now].next;
}
if (len-tot>0 && now!=-1)
memcpy(ss+tot,b[now].a,len-tot);
for (int i=0; i<len; ++i)
cout << ss[i];
cout << endl;
}

void prepare() {
init();
scanf("%s",ss);
insert(0,strlen(ss),ss);
cin >> n;
}

int p;

int main() {
/* init();*/
//scanf("%s",ss);
//insert(0,strlen(ss),ss);
//cin >> n;
prepare();
while (n--) {
scanf("%s",s);
if (s[0]=='Q') {
cin >> p;
get(p-1,1);
} else if (s[0]=='I') {
scanf("%s",s);
cin >> p;
insert(p-1,1,s);
}
}

return 0;
}


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!