使用给定的四个键打印最多的 A
让我们考虑一下,我们将尝试使用键盘书写字母“A”。我们的目标是仅使用四个键,并尝试在文本字段上写出最多的“A”。四个键是“A”、“C”、“V”和“Ctrl”。
为了写出最多的 A,我们将使用 Ctrl + A 全选,Ctrl + C 复制,Ctrl + V 粘贴。
输入和输出
Input: Number of keystrokes, say 7 Output: Maximum Number of A's with 7 keystrokes is: 9 Press A three times. Then Ctrl+A, Ctrl+C, Ctrl+V, Ctrl+V
算法
keyNumbers(keyStrokes)
输入:击键次数。
输出:使用这些击键次数可以写出的最多字母。
Begin if keyStrokes <= 6, then return keyStrokes for n := 1 to 6, do result[n-1] := n done for n := 7 to keyStrokes, do result[n-1] := 0 for breakpoint := n-3 down to 1, do curr := (n – breakpoint - 1)*result[breakpoint - 1] if curr > result[n-1], then result[n - 1] := curr done done result[keyStrokes - 1] End
范例
#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;
}输出
Enter Number of keystrokes: 7 Maximum Number of A's with 7 keystrokes is: 9
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP