题解:AT_abc465_c [ABC465C] Reverse Permutation

· · 题解

比较好的一道思维题。

分析后可以发现项数越大受到的反转影响相对来说更少,因为第 i 个字符为o时只会反转前 i 项。

因此我们可以从后往前处理,我们先假设处理到第 i 项,也就是要确定第 i 项的位置时,区间 1 \sim l-1 和区间 r+1 \sim n 的位置都已确定,区间 l\sim r 还未确定(这将在待会证明),由于我们在这之前已经确定了第 i+1 \sim n 项的位置,所以在区间 l+1 \sim r-1 对应着位置 1 \sim i,那么此时我们来看该序列被反转过几次:

由于第 1 \sim i-1 个字符为o时只能反转前 1 \sim i-1 项,不会影响第 i 项的位置,所以第 i 项就确定了。

由于每次会将 l 增加 1 或 r 减少 1,并且只有第 i 项确定后才会进行操作,那么要确定第 i 项的位置时,区间 1 \sim l-1 和区间 r+1 \sim n 的位置都已确定,区间 l\sim r 还未确定,证明了上面的假设。

::::info[场时代码] 这份代码里有思考和调试过程。

#include<bits/stdc++.h>
using namespace std;
#define int long long
#define rep(i,a,b) for(int i=a;i<=b;i++)
typedef long long ll;
typedef unsigned long long ull;
ll t=1;
ll n;
string s;
ll ans[500005];
ll l,r;
int now;//反转了几次 
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0); 
    //cin>>t;
    while(t--){
        /*
        (1 2 3 4 5)
        5 (4 3 2 1)
        5 (1 2 3) 4
        5 (1 2) 3 4
        5 2 (1) 3 4
        5 2 1 3 4
        */
        cin>>n>>s;
        l=1,r=n;
        for(int i=n;i>=1;i--){
          //cout<<s[i-1]<<endl;
          if(((s[i-1]=='o')&&(now%2==0))||((s[i-1]=='x')&&(now%2==1))){
            ans[l]=i;
            l++;
          }
          else{
            ans[r]=i;
            r--;
          }
          if(s[i-1]=='o'){
            now++;
          }
          //cout<<"l:"<<l<<" r:"<<r<<" now:"<<now<<endl;
        }
        rep(i,1,n){
          cout<<ans[i]<<' ';
        }
    }
    return 0;
}

:::: ::::info[场后代码] 这份代码更简洁。

#include<bits/stdc++.h>
using namespace std;
#define int long long
#define rep(i,a,b) for(int i=a;i<=b;i++)
typedef long long ll;
typedef unsigned long long ull;
ll t=1;
ll n;
string s;
ll ans[500005];
ll l,r;
int now;
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    while(t--){
        cin>>n>>s;
        l=1,r=n;
        for(int i=n;i>=1;i--){
          if(s[i-1]=='o'){
            now++;
          }
          if(now%2==1){
            ans[l]=i;
            l++;
          }
          else{
            ans[r]=i;
            r--;
          }
        }
        rep(i,1,n){
          cout<<ans[i]<<' ';
        }
    }
    return 0;
}

:::: ::::info[两句闲话] 我没有搞懂题目标签(完全想不到对应解法)。

喜欢就点个赞吧。