C++ 中的 4 键键盘
假设我们要尝试使用键盘输入字母“A”。我们的目标是只使用四个键并尝试在文本字段中输入尽可能多的“A”。这四个键是“A”,“C”,“V”和“Ctrl”。
为了输入最大数量的 A,我们将使用 Ctrl + A 选择全部,Ctrl + C 复制,以及 Ctrl + V 粘贴。
因此,如果输入是按键次数为 7,则输出将为 9,因为按了三次 A。
然后 Ctrl+A、Ctrl+C、Ctrl+V、Ctrl+V
为了解决这个问题,我们将遵循以下步骤:
如果 keyStrokes <= 6,则
返回 keyStrokes
对于 n := 1 到 6,执行
result[n-1] := n
对于 n := 7 到 keyStrokes,执行
result[n-1] := 0
对于断点 := n-3 到 1,执行
curr := (n – breakpoint - 1)*result[breakpoint - 1]
如果 curr > result[n-1],则
result[n - 1] := curr
result[keyStrokes - 1]
示例
让我们看看以下实现,以便更好地理解:
#include<iostream>
using namespace std;
int keyNumbers(int keystrokes){ //find number of 'A's using 4 types of keys
if (keystrokes <= 6) //if keystrokes are less than 7
return keystrokes;
int result[keystrokes]; //store intermediate results
for (int n=1; n<=6; n++) //upto 6 keystrokes, we need that number of keystrokes for max
result[n-1] = n;
for (int n=7; n<=keystrokes; n++){ //for 7th to higher result[n-1] = 0; //initially store 0 as result
for (int breakPoint=n-3; breakPoint>=1; breakPoint--){ //find breakpoint to select, copy and paste
int curr = (n-breakPoint-1)*result[breakPoint-1];
if (curr > result[n-1])
result[n-1] = curr;
}
}
return result[keystrokes-1];
}
int main(){
int keystrokes;
cout << "Enter Number of keystrokes: "; cin >> keystrokes;
cout << "Maximum Number of A's with "<<keystrokes << " keystrokes
is: "<< keyNumbers(keystrokes)<<endl;
}输入
7
输出
Enter Number of keystrokes: Maximum Number of A's with 0 keystrokes is: 0
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP