Time Limit: 1000MS | Memory Limit: 131072K | |
Total Submissions: 6670 | Accepted: 1583 |
Description
You are given a string and supposed to do some string manipulations.
Input
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.
Output
For each Q command output one line containing only the single character queried.
Sample Input
ab 7 Q 1 I c 2 I d 4 I e 2 Q 5 I f 1 Q 3
Sample Output
a d e
Source
POJ Monthly--2006.07.30, zhucheng
题意:给一个字符串,长度<=1000000; P(P<=2000)个操作,向位置添加字符或询问该处字符;
据说可以线段树,但是我不会写,就写了个分块;
分成sqrt(n+p)块,每次二分找到要对哪一块进行操作,暴力O(sqrt(n+p))插入,O(1)查找,因为sqrt(n+p)在1000左右,所以不会超时
代码:
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
const int maxn = 1000010;
using namespace std;
char s[maxn];
struct block
{
int size;
char c[1010];
void insert(int pos,char x)
{
for(int i=++size;i>pos;i--) c[i]=c[i-1];
c[pos]=x;
}
char query(int pos)
{
return c[pos];
}
void push_back(char x)
{
c[++size]=x;
}
}a[1010];
int p;
int len;
int cnt;
int sum[1010];
int find(int left,int right,int x)
{
int l=left,r=right;
int ans=0;
while(l<=r)
{
int mid=(l+r)>>1;
if(sum[mid]>=x)
{
ans=mid;
r=mid-1;
}
else
l=mid+1;
}
return ans;
}
void getnum(int r)
{
for(int i=r;i<=cnt;i++)
sum[i]=sum[i-1]+a[i].size;
}
void init()
{
len=strlen(s)+p;
cnt=sqrt(len*1.0)+1;
for(int i=0;i<len;i++)
a[i/cnt+1].push_back(s[i]);
getnum(1);
}
void inc(char x,int pos)
{
int p=find(1,cnt,pos);
a[p].insert(pos-sum[p-1],x);
getnum(p);
}
char search(int pos)
{
int p=find(1,cnt,pos);
return a[p].query(pos-sum[p-1]);
}
int main()
{
scanf("%s",s);
scanf("%d",&p);
init();
while(p--)
{
char f[10];
int x;
char ss[10];
scanf("%s",f);
if(f[0]=='I')
{
scanf("%s%d",ss,&x);
inc(ss[0],x);
}
else
{
scanf("%d",&x);
printf("%c\n",search(x));
}
}
return 0;
}