Official

D - LR insertion Editorial by en_translator


By reversing the order of operations, it can be rephrased as follows:

Initially we have \(A=(N)\).
For each \(i=N,N-1,\ldots,1\), do the following.

  • If \(s_i\) is L, append \(i-1\) to the tail of \(A\).
  • If \(s_i\) is R, prepend \(i-1\) to the head of \(A\).

This can be implemented with a double-ended queue.
The computational complexity is \(O(N)\).

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

signed main(){
    ll n;string s;
    cin>>n>>s;
    deque<ll>a={n};
    for(ll i=n-1;i>=0;i--){
        if(s[i]=='L')a.push_back(i);
        else a.push_front(i);
    }
    for(ll i=0;i<=n;i++){
        if(i<n)cout<<a[i]<<" ";
        else cout<<a[i]<<endl;
    }
    return 0;
}

posted:
last update: