﻿ 算法 – 计算将一个排列转换为另一个排列所需的相邻交换 - 代码日志

#### 算法 – 计算将一个排列转换为另一个排列所需的相邻交换

We’re given two sequences of lowercase latin alphabet letters.
They’re both the same length and have the same amount of given types
of letters (the first has an equal number of t’s as the second and so
on). We are required to find the minimum number of swaps (by “swap” we mean changing
the order of two neighboring
letters) required to
transform the first sequence into the second. We
can safely assume every two sequences CAN be transformed
into each other. We could do this with brute-force, but the sequences are too long for that.

Input:
The length of the sequences (at least 2, at most 999999) and
then two sequences.

Output:
An integer representing the number of swaps needed for the
sequences to become the same.

Example:
{5, aaaaa, aaaaa} should output {0},
{4, abcd, acdb} should output {2}.

``````for ( int i = 0; i < s1.size(); ++i )
Q[ s2[i] ].push_back(i); // basically, Q is a vector [0 .. 25] of lists

temp[0 .. 25] = {0}
for ( int i = 0; i < s1.size(); ++i )
P[i + 1] = 1 + Q[ s1[i] ][ temp[ s1[i] ]++ ];
``````

``````    1234
s1: abcd
s2: acdb
Q: Q[a = 0] = {0}, Q[b = 1] = {3}, Q[c = 2] = {1}, Q[d = 3] = {2}
P: P = 1, P = 4 (because the b in s1 is on position 4 in s2), P = 2
P = 3
``````

P有2次反转(4 2和4 3)，所以这是答案。