当前位置: 代码迷 >> 综合 >> 牛客多校暑假训练营2020 (第三场) B-【Classical String Problem】
  详细解决方案

牛客多校暑假训练营2020 (第三场) B-【Classical String Problem】

热度:7   发布时间:2024-01-31 02:18:08.0

B-Classical String Problem

题目描述:
Given a string S consists of lower case letters. You’re going to perform Q operations one by one. Each operation can be one of the following two types:

Modify: Given an integer x. You need to modify S according to the value of x. If x is positive, move the leftmost x letters in S to the right side of S; otherwise, move the rightmost |x| letters in S to the left side of S.
Answer: Given a positive integer x. Please answer what the x-th letter in the current string S is.
输入描述
输出描述:

For each answer operation, please output a letter in a separate line representing the answer to the operation. The order of the output should match the order of the operations in the input.

输入:

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

输出:

n
o
w

备注:

Initially, S is ‘nowcoder’, six operations follow.
? The 1-st operation is asking what the 1-st letter is. The answer is ‘n’.
? The 2-nd operation is to move the leftmost 4 letters to the rightmost side, so S is modified to ‘odernowc’.
? The 3-rd operation is asking what the 6-th letter is. The answer is ‘o’.
? The 4-th operation is to move the rightmost 3 letters to the leftmost side, so S is modified to ‘owcodern’.
? The 5-th operation is to move the leftmost 1 letter to the rightmost side, so S is modified to ‘wcoderno’.
? The 6-th operation is asking what the 1-st letter is. The answer is ‘w’.

刚开始按照题目意思敲了个模拟,用string的加法和分割来做,但是会tttt,其实使用指针会更方便,我指针没太学好,就找一下规律,把字符串看成一个环,每次变形我们只需要改动这个字符串的初始位置,就可以了。
还有一个小问题:在输入字符串时,碰到了从键盘输入字符的问题。

对于scanf()而言,%c是个较为特殊的说明符。 %c前没空格,scanf()将读取标准输入流中的第一个字符,%c前有空格,scanf()则读取标准输入流中第一个非空白字符
为什么scanf的%c前为什么要加空格https://blog.csdn.net/u010850265/article/details/9136679

代码如下:

#include<bits/stdc++.h> //万能头文件
using namespace std;
const int maxn=20000006;typedef long long ll;
char s[maxn];
int main(){scanf("%s",&s);int t,k=0,len;len=strlen(s);scanf("%d",&t);while(t--){char op;ll x;scanf(" %c %lld",&op,&x);//在%c前面加入空格跳过空白符if(op=='A') printf("%c\n",s[(k+len+x-1)%len]);else if(op=='M') k=(k+len+x)%len;}return 0;
}

**
附上大神的标准题解源代码
在这里插入图片描述

#include<bits/stdc++.h>
#define N 100005
using namespace std;
map<int,int>G;
int a[N],n;char s[N];
int main(){//freopen("test7.in","r",stdin);scanf("%d",&n);scanf("%s",s+1);for (int i=1;i<=n;i++)a[i]=a[i-1]+((s[i]=='1')?1:-1);//a[r]-a[l-1]==0int ans=0;G[0]=0;for (int i=1;i<=n;i++)if (G.find(a[i])!=G.end())ans=max(ans,i-G[a[i]]);elseG[a[i]]=i;int zero=0,one=0;for (int i=1;i<=n;i++)if (s[i]=='0') zero++;else one++;printf("%d %d\n",ans,min(zero,one)*2);
}
  相关解决方案