Optimal Keystrokes to Generate a String on a Limited Keyboard
Optimal Keystrokes to Generate a String on a Limited Keyboard
You are given a computer with a keyboard that has only three keys: 'a' key, Shift key, and Caps Lock key. The Caps Lock key has a light on it. Initially, the light on the Caps Lock key is off, and the screen shows an empty string.
You can perform the following three actions any number of times in any order:
- Spend X milliseconds to press only the 'a' key. If the Caps Lock light is off, 'a' is appended to the string on the screen; if it's on, 'A' is appended.
- Spend Y milliseconds to press the 'a' key and Shift key simultaneously. If the Caps Lock light is off, 'A' is appended to the string on the screen; if it's on, 'a' is appended.
- Spend Z milliseconds to press the Caps Lock key. This toggles the Caps Lock light: if it's off, it turns on; if it's on, it turns off.
Given a string 'S' consisting of 'A' and 'a', determine the minimum number of milliseconds you need to spend to make the string shown on the screen equal to 'S'.
Example
Let's say:
- X = 2 milliseconds
- Y = 3 milliseconds
- Z = 1 millisecond
- S = "AaA"
Here's one way to generate the string 'AaA':
- Press 'a' (X = 2 milliseconds) -> 'a'
- Press 'a' + Shift (Y = 3 milliseconds) -> 'aA'
- Press 'a' (X = 2 milliseconds) -> 'aAa'
- Press Caps Lock (Z = 1 millisecond) -> 'AaA'
Therefore, the minimum number of milliseconds needed is 2 + 3 + 2 + 1 = 8 milliseconds.
C++ Code Implementation
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
int x, y, z;
string s;
cin >> x >> y >> z >> s;
int n = s.length();
int ans = 0;
bool caps_lock = false;
for(int i=0; i<n; i++) {
char c = s[i];
if(caps_lock) {
if(c >= 'a' && c <= 'z') {
ans += y; // press a+Shift
caps_lock = false;
}
} else {
if(c >= 'A' && c <= 'Z') {
ans += z; // press Caps Lock
ans += x; // press a
caps_lock = true;
} else {
ans += x; // press a
}
}
}
cout << ans << endl;
return 0;
}
This C++ code efficiently calculates the minimum time needed to generate the target string by iterating through the string, considering the Caps Lock state, and optimizing keystrokes based on the current character and the Caps Lock status.
原文地址: https://www.cveoy.top/t/topic/ojeW 著作权归作者所有。请勿转载和采集!