Big String-POJ2887塊狀數組

Time Limit: 1000MS Memory Limit: 131072K

Description

You are given a string and supposed to do some string manipulations.ios

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.git

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:markdown

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.app

Output

For each Q command output one line containing only the single character queried.ui

Sample Input

ab
7
Q 1
I c 2
I d 4
I e 2
Q 5
I f 1
Q 3spa

Sample Output

a
d
ecode

Source

POJ Monthly–2006.07.30, zhuchengorm

給一個字符串,有兩種操做,在第k個前面插入一個字符,和查找第k個字符,因爲字符串比較的長,可是操做比較都少,因此比較適合分塊。ip

#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;
}
相關文章
相關標籤/搜索