数据结构 - Classical String Problem - 2020牛客暑期多校训练营(第三场)
题意:
给定一个字符串S,以及Q组询问,
分成两种情况:
A x:输出S的第x个字符。
Q x:若x>0,表示将S的长度为x前缀转移到S的尾部。
若x<0,表示将S的长度为∣x∣的后缀转移到S的首部。
输入:
首行包括字符串S。
第二行包括整数Q。
接着Q行表示Q组操作。
每组操作包括字符c,和整数x。
示例1
输入
nowcoder
6
A 1
M 4
A 6
M -3
M 1
A 1
输出
n
o
w
数据范围:
2≤∣S∣≤2×106,1≤Q≤8×105,
c=′M′ or ′A′
c=′M′,1≤∣x∣<∣S∣
c=′A′,1≤x≤∣S∣
分析:
指针维护字符串的首字母位置即可。查询时增加偏移量x,就能够在O(1)的时间内快速查询。
c=′M′,x>0:更新st=st′,ed=ed′。
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;
}