POJ2887 分块

Big String
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:

  1. 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.
  2. 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;
}
感觉自己水平越来越差了,,,为什么铺天盖地都是数据结构题!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值