C - Adjacent Swaps Editorial by en_translator
Fundamental Idea
Basically, simulate the operations by storing the integer written on the ball at each position and find the resulting permutation.
Let \(val[i]\) be the variable that represents the integer written on the \(i\)-th ball from the left.
Initially, the \(i\)-th (\(1 \leq i \leq N\)) ball from the left has an integer \(i\) written on it.
So let us initialize \(val\) as follows:
vector<int> val(N+1);
for(int i=1;i<=N;i++)val[i] = i;
The \(Q\) operations can be simulated as follows:
for(int i=0;i<Q;i++){
for(int j=1;j<=N;j++){
if(val[j]==x[i]){
if(j!=N)swap(val[j],val[j+1]);
else swap(val[j],val[j-1]);
break;
}
}
}
However, the time complexity of this simulation is \(\mathrm{O}(NQ)\), which needs an improvement to fit in the time limit under the Constraint of this problem.
Improvement to \(\mathrm{O}(Q)\)
In the code above, we spend \(\mathrm{O}(N)\) time to find \(j\) such that \(val[j]=x[i]\) in each of \(Q\) iterations, but we can manage the variable \(pos[j]\) to store the position of the ball with the integer \(j\) written on it, so that it can be found in an \(\mathrm{O}(1)\) time, which enables us to solve this problem fast enough.
Sample code
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
cin>>N;
vector<int> val(N+1),pos(N+1);
for(int i=1;i<=N;i++)val[i] = i,pos[i] = i;
int Q;
cin>>Q;
vector<int> x(Q);
for(int i=0;i<Q;i++)cin>>x[i];
for(int i=0;i<Q;i++){
int p0 = pos[x[i]];
int p1 = p0;
if(p0!=N)p1++;
else p1--;
int v0 = val[p0];
int v1 = val[p1];
swap(val[p0],val[p1]);
swap(pos[v0],pos[v1]);
}
for(int i=1;i<=N;i++){
if(i!=1)cout<<' ';
cout<<val[i];
}
cout<<endl;
return 0;
}
posted:
last update: