洛谷P10058 Reverse and Rotate 最简单的题解
思路
1.
左移和右移之间是可以相互抵消的,所以我们可以把右移当作 - ,左移当作 + ,进行累加,最后统一操作。
2.
每次翻转要将累加结果取相反数,且每两次翻转可以抵消(但还要取相反数)。
3.
如果翻转次数为奇数,则将原字符串翻转。
4.
根据累加结果进行移动。
代码
#include<iostream>
using namespace std;
int main(){
// "cin" 关同步(加快速度)
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
// 输入
string s;
long long n;
cin>>s>>n;
long long l=0; //累加器
bool f=true; //翻转统计器
// 统计
while(n--){
string t;
cin>>t;
if(t=="rev"){
f=!f; // 统计翻转
l=-l; // 取相反数
}
else{
long long x;
cin>>x;
if(t=="<"){
l+=x%s.size(); // 统计左移
}
else{
l-=x%s.size(); // 统计右移
}
}
}
// 翻转
string ans;
if(f==false){
for(int i=int(s.size())-1;i>=0;i--){
ans+=s[i];
}
}
else{
ans=s;
}
// 移动+输出
if(l<0){ // 处理右移
l=-l;
l%=int(ans.size());
string t=ans.substr(ans.size()-l,l);
/*
"substr" 为截取字符串,第一个参数为起始位置,
第二个参数为截取字符数。
*/
t+=ans.substr(0,ans.size()-l);
cout<<t;
}
else{ // 处理左移
l%=int(ans.size());
string t=ans.substr(0,l);
t=ans.substr(l,ans.size()-l)+t;
cout<<t;
}
}
你学会了吗?