F - Word Ladder Editorial by en_translator
Let \(N\) be the length of the string, and \(x\) be the number of \(i\) with \(S_i \neq T_i\).
It turns out that the number of elements in the answer, or the minimum possible number of operations, is \(x\), and every operation picks an \(i\) with \(S_i \neq T_i\) to replace \(S_i\) with \(T_i\).
We consider the order of operation.
Since we can pick \(i\) with \(S_i \neq T_i\) and replace \(S_i\) with \(T_i\) in any order, for lexicographical minimization it is sufficient to try all the possible operations and decide to do the operation that results in the lexicographically minimum string.
Under the constraints of this problem, it is sufficient to simply repeat brute-forcing, which can be done done in a total of \(O(N^3)\) time.
We can even speed it up.
When \(S_i\) is replaced with \(T_i\), the string becomes lexicographically larger if \(S_i < T_i\) and smaller if \(S_i > T_i\).
Thus, if there is an \(i\) with \(S_i > T_i\), it is optimal to apply an operation against such \(i\), especially the minimum such \(i\). Also, if there is no \(i\) with \(S_i < T_i\), it is optimal to apply an against the maximum \(i\) with \(S_i > T\i\).
It is sufficient to repeat this as long as \(S \neq T\), and the total time complexity is evaluated as \(O(N^2)\).
Sample code (\(O(N^3)\))
#include <bits/stdc++.h>
using namespace std;
int main() {
string s, t;
cin >> s >> t;
vector<string> ans;
int n = s.size();
while (s != t) {
string nxt(n, 'z');
for (int i = 0; i < n; i++) {
if (s[i] != t[i]) {
string tmp = s;
tmp[i] = t[i];
nxt = min(nxt, tmp);
}
}
ans.push_back(nxt);
s = nxt;
}
int sz = ans.size();
cout << sz << '\n';
for (string e : ans) cout << e << '\n';
}
Sample code (\(O(N^2)\))
#include <bits/stdc++.h>
using namespace std;
int main() {
string s, t;
cin >> s >> t;
vector<string> ans;
vector<int> v;
int n = s.size();
for (int i = 0; i < n; i++) {
if (s[i] > t[i]) v.push_back(i);
}
for (int i = n - 1; i >= 0; i--) {
if (s[i] < t[i]) v.push_back(i);
}
int sz = v.size();
for (int i = 0; i < sz; i++) {
s[v[i]] = t[v[i]];
ans.push_back(s);
}
cout << sz << '\n';
for (string e : ans) cout << e << '\n';
}
posted:
last update: