1015B - Obtaining the String - CodeForces Solution


implementation *1200

Please click on ads to support us..

Python Code:

N = int(input())
s = input()
t = input()
if sorted(s) != sorted(t):
  print(-1)
else:
  ans = []
  
  for i in range(N):
    a = t[i]
    b = s.index(a)
    for j in range(b,0,-1):
      ans.append(str(j+i))
    s = s[:b] + s[b+1:]
  print(len(ans))
  print(" ".join(ans))

C++ Code:

#include <bits/stdc++.h>
using namespace std;
/*#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> indexed_set;*/

// file I/O
/*ifstream ifs("input.txt");
ofstream ofs("output.txt");
#define cin ifs
#define cout ofs*/

/* ------------------------------------ */

template <typename T>
ostream& operator <<(ostream& output, const vector<T>& data) {
    for (const T& x : data)
        output << x <<" ";
    return output;
}
 
template<typename T>
istream& operator>>(istream& input,vector<T>& data) {
    for (auto& item : data)
        input >> item;
    return input;
}

/* ------------------------------------ */

typedef long long ll;
typedef long double ld;

#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()

#define SUM(v) accumulate(all(v), 0LL)
#define MIN(v) *min_element(all(v))
#define MAX(v) *max_element(all(v))

#define endl "\n"

const ll inf = 1e18;
const ll mod = 1e9 + 7;
const int MAX = 2e5+5;

/////////////////////////////////////////////

void solve() {
    ll n; cin>>n;
    string s,t; cin>>s>>t;
    vector<ll> ans;
    for(ll i=0; i<n; ++i) {
    	if(s[i] == t[i]) continue;
    	ll last = -1;
    	for(ll j=i+1; j<n; ++j) {
    		if(s[j] == t[i]) {
    			last = j;
    			break;
    		}
    	}
    	if(last == -1) {
    		cout<<-1;
    		return;
    	}
    	for(ll idx = last-1; idx>=i; --idx) {
    		swap(s[idx],s[idx+1]);
    		ans.push_back(idx+1);
    	}
    }
    cout<<ans.size()<<endl<<ans;
    return;
}

int main() {
    ios_base::sync_with_stdio(0);cin.tie(0);
    ll tc=1; 
    // cin>>tc;
    for(ll i=1; i<=tc; ++i) {
    	solve();
    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

454A - Little Pony and Crystal Mine
2A - Winner
1622B - Berland Music
1139B - Chocolates
1371A - Magical Sticks
1253A - Single Push
706B - Interesting drink
1265A - Beautiful String
214A - System of Equations
287A - IQ Test
1108A - Two distinct points
1064A - Make a triangle
1245C - Constanze's Machine
1005A - Tanya and Stairways
1663F - In Every Generation
1108B - Divisors of Two Integers
1175A - From Hero to Zero
1141A - Game 23
1401B - Ternary Sequence
598A - Tricky Sum
519A - A and B and Chess
725B - Food on the Plane
154B - Colliders
127B - Canvas Frames
107B - Basketball Team
245A - System Administrator
698A - Vacations
1216B - Shooting
368B - Sereja and Suffixes
1665C - Tree Infection