H. Neil's Machine
time limit per test: 1 second
memory limit per test: 256 megabytes
Dr. Neil Watts, a Technician Specialist at Sigmund Corp., has developed a prototype machine that is capable of modifying the memories of terminally ill patients. He represents these memories using strings.
In this scenario, we use two strings of the same length, denoted as S and T. Both of these strings are composed of only lowercase English letters. The string S represents the patient's original memories, while the string T represents the target memories. The ultimate goal is to perform several operations on string S until it becomes identical to string T.
The memory modification machine performs operations using a basic function called rshift k where 1≤k≤25. This function changes a letter to the k-th letter following it in the alphabet. In this context, the letter following z is considered to be a.
However, due to the potential for memory modifications to alter the course of the timeline, Dr. Watts can only apply the rshift k operation to a suffix of string S during each operation. The value of k and the length of the suffix can be arbitrarily chosen for each operation.
For instance, the string uvwxyz would be uvzabc if rshift 3 is applied to the suffix beginning with w.
As excessive memory operations can lead to unintended consequences, Dr. Watts needs to minimize the number of operations performed. Therefore, he needs your help to determine the minimum number of operations required to transform string S into string T.
Input
The first line contains an integer n (1≤n≤2⋅), denoting the length of strings.
The second line contains a string S consisting of n lowercase English letters.
The third line contains a string T consisting of n lowercase English letters.
Output
Output an integer representing the minimum number of operations required to transform string S into string T.
Examples
input
4
aaaa
aaaa
output
0
input
9
aaaaaaaaa
aaabbbaaa
output
2
input
17
sofiawilumerrymee
sofiawillumarryme
output
8
input
32
takethesebrokenwingandlearntofly
takethesesunkeneyesandlearntosee
output
12
【思路分析】
思维。由于每次操作只修改后缀,令dp[i] = (s[i] - t[i]) > 0 ? 'z' - s[i] + t[i] - 'a' + 1 : t[i] - s[i], 只需对dp数组计数dp[i] != dp[i+1]的部分即可。
#include <iostream>
#include <vector>
#include <unordered_map>
#include <map>
#include <cmath>
#include <algorithm>
#include <climits>
#include <stack>
#include <cstring>
#define i64 long long
using namespace std;
i64 dp[200001];
void solve() {
i64 n;
cin >> n;
string s, t;
cin >> s >> t;
for (int i = 0; i < n; ++i) dp[i] = (s[i] - t[i]) > 0 ? 'z' - s[i] + t[i] - 'a' + 1 : t[i] - s[i];
i64 cnt = 0;
for (int i = n - 2; i >= 0; --i) {
if (dp[i] != dp[i + 1]) ++cnt;
}
if (dp[0] > 0) cnt++;
cout << cnt;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int t = 1;
// cin >> t;
while (t--) {
solve();
}
return 0;
}