Big String 块状数组(或者说平方分割)
2015-04-04 09:21
232 查看
Big String
给一个字符串,长度不超过 106,有两种操作:
1. 在第 i 个字符的前面添加一个字符 ch
2. 查询第 k 个位置是什么字符
操作的总数不超过 2000
如果直接模拟的话,移动到后面的数据量太大。我们分块的话,就可以优化,减少移动的量。 很典型的块状数组。块状数组的next指向的是一块,而不是一个。这里用整数代替了指针。
每一个块就是一个对象。这题用面向对象编程。
给一个字符串,长度不超过 106,有两种操作:
1. 在第 i 个字符的前面添加一个字符 ch
2. 查询第 k 个位置是什么字符
操作的总数不超过 2000
如果直接模拟的话,移动到后面的数据量太大。我们分块的话,就可以优化,减少移动的量。 很典型的块状数组。块状数组的next指向的是一块,而不是一个。这里用整数代替了指针。
每一个块就是一个对象。这题用面向对象编程。
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #include <string> #include <vector> #include <set> #include <map> #include <stack> #include <queue> #include <sstream> #include <iomanip> using namespace std; typedef long long LL; const int INF=0x4fffffff; const int EXP=1e-5; const int MS=2100; struct node { int size,next; char str[MS]; void push(char ch) { str[size++]=ch; } void insert(int pos,char ch) { for(int i=size++;i>pos;i--) str[i]=str[i-1]; str[pos]=ch; } }nodes[MS]; char S[500*MS]; int SIZE,cnt,Q; void input() { scanf("%s",S); scanf("%d",&Q); int len=strlen(S); SIZE=(int)sqrt(0.1+len+Q); cnt=0; nodes[cnt].size=0; for(int i=0;i<len;i++) { if(nodes[cnt].size>=SIZE) { nodes[cnt].next=cnt+1; nodes[++cnt].size=0; } nodes[cnt].push(S[i]); } nodes[cnt].next=-1; } //设一个块的最大容量为2*SIZE,当满了就要从后面使用一块来补充 void updata(int id) { if(nodes[id].size<2*SIZE) // 我们是在区间插入一个字符后在更新,所以要留一个位置 return ; ++cnt; int i,j,k=nodes[id].size; for(i=SIZE,j=0;i<k;i++,j++) nodes[cnt].str[j]=nodes[id].str[i]; nodes[cnt].size=j; nodes[id].size=SIZE; nodes[cnt].next=nodes[id].next; nodes[id].next=cnt; } void solve() { int i,j,pos; char cmd[MS]; for(i=0;i<Q;i++) { scanf("%s",cmd); if(cmd[0]=='Q') { scanf("%d",&pos); for(j=0;pos>nodes[j].size;j=nodes[j].next) pos-=nodes[j].size; printf("%c\n",nodes[j].str[pos-1]); } else { scanf("%s%d",cmd,&pos); for(j=0;pos>nodes[j].size&&nodes[j].next!=-1;j=nodes[j].next) pos-=nodes[j].size; nodes[j].insert(min(pos-1,nodes[j].size),cmd[0]); updata(j); } } } int main() { input(); solve(); return 0; }
相关文章推荐
- D. Powerful array 莫队算法或者说块状数组 其实都是有点优化的暴力
- Poj 2887 Big String(块状数组)
- 数据结构与算法之:块状链表(或者叫块状数组)
- POJ2887 Big String(块状数组)
- 【POJ 2887】Big String(块状数组)
- Big String-POJ2887块状数组
- Big String-POJ2887块状数组
- JS实现textarea通过换行或者回车把多行数字分割成数组并且去掉数组中空的值
- 实现任意找到一个字符或者字符串将整个字符串分割成若干个字符串保存到字符数组当中
- JAVA两个数组间元素的比较(找出相同或者不同元素)
- JS中,split()用法(将字符串按指定符号分割成数组)
- sql按指定符号分割字符串,返回分割后指定索引的第几个元素,象数组一样方便
- php 算法之分割数组,不用array_chunk(),算法之二,取数组的差值,不用array_diff()
- php 字符串的连接、分割,数组、include require
- 随笔 JS 字符串 分割成字符串数组 并动态添加到指定ID的DOM 里
- js分割字符串变成数组
- 数组分割,把数组分割成和相等的两部分--递归方法
- 九章算法面试题84 奇偶分割数组
- 数组分割
- js split 的用法和定义 js split分割字符串成数组