POJ 2887 Big String(块状链表)
2013-08-19 13:34
344 查看
题目大意
给一个字符串,长度不超过 106,有两种操作:1. 在第 i 个字符的前面添加一个字符 ch
2. 查询第 k 个位置是什么字符
操作的总数不超过 2000
做法分析
好多不同的做法都可以搞人生第一个块状链表,记录下
块状链表的思想其实挺简单的,传统的链表每个节点只记录一个字符,块状链表的每个节点记录的是 sqrt(n) 个信息,一个长度为 n 的字符串就被分成了 sqrt(n) 个。这样,查询和插入字符的操作就变成了 sqrt(n)级别的了,对于这题 2000 个操作来讲,时间复杂度还能忍受
这题只有插入和查询操作,所以写起来非常简单
不过我不喜欢使用指针搞来稿去的,所以写的数组形式的
参考代码
#include <iostream> #include <cstring> #include <cstdio> using namespace std; const int N=2000, LEN=2000; struct Block_List { struct Node { char buff[LEN]; int next, Size; void init() { memset(buff, 0, sizeof buff); next=-1, Size=0; } } List ; int head, tot; void init(char S[]) { head=tot=0; List[tot++].init(); for(int i=0, cur=head; S[i]; cur=List[cur].next) { for(int j=0; j<LEN && S[i]; j++, i++) { List[cur].buff[j]=S[i]; List[cur].Size++; } if(S[i]) { List[tot].init(); List[cur].next=tot++; } } for(int cur=head; cur!=-1; cur=List[cur].next) if(List[cur].Size==LEN) Split(cur); } void Split(int id) { List[tot].init(); for(int i=LEN/2; i<LEN; i++) { List[tot].buff[i-LEN/2]=List[id].buff[i]; List[tot].Size++; List[id].buff[i]=0; List[id].Size--; } List[tot].next=List[id].next; List[id].next=tot++; } void Insert(int pos, char val) { int cur=head; while(pos>List[cur].Size && List[cur].next!=-1) { pos-=List[cur].Size; cur=List[cur].next; } if(pos>=List[cur].Size) List[cur].buff[List[cur].Size]=val; else { for(int i=List[cur].Size; i>pos; i--) List[cur].buff[i]=List[cur].buff[i-1]; List[cur].buff[pos]=val; } List[cur].Size++; if(List[cur].Size==LEN) Split(cur); } char Find(int pos) { int cur=head; while(pos>List[cur].Size) pos-=List[cur].Size, cur=List[cur].next; return List[cur].buff[pos-1]; } }; Block_List hehe; char buff[1000006], S[2]; int n; int main() { // freopen("in", "r", stdin); scanf("%s", buff); hehe.init(buff); scanf("%d", &n); for(int i=0, pos; i<n; i++) { scanf("%s", buff); if(buff[0]=='I') { scanf("%s%d", S, &pos); hehe.Insert(pos-1, S[0]); } else { scanf("%d", &pos); printf("%c\n", hehe.Find(pos)); } } return 0; }
POJ 2887
题目链接 & AC 通道
POJ 2887 Big String相关文章推荐
- [POJ 2887] Big String [块状链表]
- POJ 2887 Big String(块状链表)
- poj 2887 Big String 块状链表
- poj 2887 Big String(块状链表)
- poj 2887 块状链表 单点插入+单点查询
- poj2882 Big String(数据结构 - 块状链表)
- Poj 2887 Big String(块状数组)
- 【POJ 2887】Big String(块状数组)
- POJ-2887(块状链表)
- POJ 2887 Big String
- 块状链表(附NOI 2003 Editor,POJ 2131 Key Insertion)
- Big String(poj 2887)
- poj 2887 Big String
- poj 2887 块状数组
- POJ 2887 Big String 线段树 离线处理
- poj 2887 Big String
- 【POJ2887】【块状链表】Big String
- POJ2887 Big String 块状链表
- poj 2828 块状链表 OR 线段树 OR 树状数组
- 【POJ2887】【块状链表】Big String