数据结构 - Classical String Problem - 2020牛客暑期多校训练营(第三场)

数据结构 - Classical String Problem - 2020牛客暑期多校训练营(第三场)

题意:

S Q 给定一个字符串S,以及Q组询问,

分成两种情况:

A   x S x A\ x:输出S的第x个字符。

Q   x x > 0 S x S Q\ x:若x>0,表示将S的长度为x前缀转移到S的尾部 。

    x < 0 S x S \qquad\ \ \ 若x<0,表示将S的长度为|x|的后缀转移到S的首部。

输入:

S 首行包括字符串S。

Q 第二行包括整数Q。

Q Q 接着Q行表示Q组操作。

c x 每组操作包括字符c,和整数x。

示例1
输入

nowcoder
6
A 1
M 4
A 6
M -3
M 1
A 1

输出

n
o
w

数据范围:

2 S 2 × 1 0 6 , 1 Q 8 × 1 0 5 , 2≤∣S∣≤2×10^6, 1≤Q≤8×10^5,

c = M   o r   A c = 'M' \ or\ 'A'

c = M , 1 x < S c = 'M', 1≤∣x∣<|S |

c = A , 1 x S c = 'A', 1≤x≤|S|


分析:

x O ( 1 ) 指针维护字符串的首字母位置即可。查询时增加偏移量x,就能够在O(1)的时间内快速查询。

c = M x > 0 s t = s t e d = e d c='M',x>0:更新st=st',ed=ed'。

在这里插入图片描述
c = M x < 0 s t = s t e d = e d c='M',x<0:更新st=st',ed=ed'。
在这里插入图片描述

代码:

#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <iostream>
#include <algorithm>

using namespace std;

const int N=2e6+10;

int q;
char str[N];

int main()
{
    scanf("%s",str);
    int len=strlen(str);
    int st=0,ed=len-1;
    
    char op[2];
    int x;
    cin>>q;
    while(q--)
    {
        scanf("%s%d",op,&x);
        if(*op=='A') printf("%c\n",str[(st+x-1)%len]);
        else
        {
            if(x>0) 
            {
                st=(st+x)%len;
                ed=(st-1+len)%len;
            }
            else
            {
                st=(ed+x+1+len)%len;
                ed=(ed+x+len)%len;
            }
        }
    }
    
    return 0;
}

猜你喜欢

转载自blog.csdn.net/njuptACMcxk/article/details/107453583