Time Limit: 1000MS | Memory Limit: 131072K |
---|
You are given a string and supposed to do some string manipulations.
The first line of the input contains the initial string. You can assume that it is non-empty and its length does not exceed 1,000,000.
The second line contains the number of manipulation commands N (0 < N ≤ 2,000). The following N lines describe a command each. The commands are in one of the two formats below:
I ch p: Insert a character ch before the p-th character of the current string. If p is larger than the length of the string, the character is appended to the end of the string.
Q p: Query the p-th character of the current string. The input ensures that the p-th character exists.
All characters in the input are digits or lowercase letters of the English alphabet.
For each Q command output one line containing only the single character queried.
ab
7
Q 1
I c 2
I d 4
I e 2
Q 5
I f 1
Q 3
a
d
e
POJ Monthly–2006.07.30, zhucheng
给一个字符串,有两种操作,在第k个前面插入一个字符,和查找第k个字符,由于字符串比较的长,但是操作比较都少,所以比较适合分块。
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <string>
#include <vector>
#include <queue>
#include <iostream>
#include <algorithm>
using namespace std;
const int Max = 2000;//分块的大小
int next[2100];
int Size[2100];
char s[2100][2100];
char str[1000100];
int Num,top;
void Init()
{
for(int i=0;i<2100;i++)
{
next[i]=-1;
Size[i]=0;
}
Num = 0;
}
void Build()
{
int len =strlen(str),top;
for(int i=0;i<len;)
{
top = Num++;
for(int j=0;j<Max&&i<len;j++,i++)
{
s[top][j] = str[i];
Size[top]++;
}
if(i<len)
{
next[top]=Num;
}
}
}
void Insert(int st,char c,int num)//插入字符
{
for(int i = Size[st];i>=num;i--) s[st][i] = s[st][i-1];
s[st][num-1] = c;
Size[st]++;
}
void Mer(int i)//当一个块比较的时候,分成两部分,但是加上这个操作,结果就不对,望诸位大神指点一下。
{
int top=Num++;
Size[top] = 0;
for(int j=Size[i]/2;j<Size[i];j++)
{
s[top][j-Size[i]/2] = s[i][j];
Size[top]++;
Size[i]--;
}
next[top] = next[i];
next[i] = top;
}
int main()
{
Init();
scanf("%s",str);
Build();
int n;
char Op[5],c[5];
int u;
scanf("%d",&n);
while(n--)
{
scanf("%s",Op);
if(Op[0]=='Q')
{
scanf("%d",&u);
int i=0;
for(i =0;i!=-1&&u>Size[i];i=next[i]) u-=Size[i];
printf("%c\n",s[i][u-1]);
}
else
{
scanf("%s %d",c,&u);
int i = 0;
for(i=0;next[i]!=-1&&u>Size[i];i = next[i]) u-=Size[i];
if(u>Size[i])
{
u = Size[i]+1;
}
Insert(i,c[0],u);
}
}
return 0;
}