【每天一道算法题】Numeric Keypad
題目描述
The numberic keypad on your mobile phone looks like below:
123
456
789
?0
?suppose you are holding your mobile phone with single hand. Your thumb points at digit 1. Each time you can 1)press the digit your thumb pointing at.2)moveyour thumb right,3)move your thumb down. Moving your thumb left or up is not allowed.
?By using the numeric keypad under above constrains, you can produce some numbers like 177 or 480 while producing other numbers like 590 or 52 is impossible.
?Given a number K, find out the maximum number less than or equal to K that can be produced.
輸入描述:
the first line contains an integer T, the number of testcases.Each testcase occupies a single line with an integer K.
For 50%of the data ,1<=K<=999.
For 100% of the data, 1<=K<=10^500,t<=20.
輸出描述:
for each testcase output one line, the maximum number less than or equal to the corresponding K that can be produced.?
輸入例子:
325
83
131
?
輸出例子:
2580
129
劍指offer公司真題部分,微軟的題目。 根據題意,可以知道的是,按下某個鍵后,這個鍵左方及上方的鍵不能再用了。例如按下了[5]:
所以我們可以得到一張表,以表示按下某個鍵后還剩下的合法按鍵:
#include <iostream> #include <vector> #include <string> #include <queue> using namespace std; int pad[10][10] = {{ 0 },{ 0,1,2,3,4,5,6,7,8,9 },{ 0,2,3,5,6,8,9 },{ 3,6,9 },{ 0,4,5,6,7,8,9 },{ 0,5,6,8,9 },{ 6,9 },{ 0,7,8,9 },{ 0,8,9 },{ 9 }}; int last[] = { 0,9,6,2,6,4,1,3,2,0 };string maxnum(string& s1) {string s2;s2.push_back(s1[0]);int len = s1.length();for (int i = 1; i < len; ) {int need = s1[i] - '0';int key = s2.back() - '0';int j = 0;for (j = last[key]; j >= 0; j--){if (pad[key][j] == need) {i++;s2.push_back(pad[key][j] + '0');break;}}if (j < 0) {for (j = last[key]; j >= 0; j--){if (pad[key][j] < need) {s2.push_back(pad[key][j] + '0');key = s2.back() - '0';for (int j = s2.size(); j < len; j++)s2.push_back(pad[key][last[key]] + '0');return s2;}}}if (j < 0) {need = key;s2.pop_back();if (s2.size() == 0) {s2.push_back(need - 1 + '0');key = s2.back() - '0';for (int j = s2.size(); j < len; j++)s2.push_back(pad[key][last[key]] + '0');return s2;}key = s2.back()-'0';for (j = last[key]; j >= 0; j--){if (pad[key][j] < need) {s2.push_back(pad[key][j] + '0');key = s2.back() - '0';for (int j = s2.size(); j < len; j++)s2.push_back(pad[key][last[key]]+'0');return s2;}}}}return s2; }int main() {int num;cin >> num;vector<string> vec(num,"");for (int i = 0; i < num; i++)cin >> vec[i];for (int i = 0; i < num; i++)cout << maxnum(vec[i]) << endl;return 0; }
?
轉載于:https://www.cnblogs.com/LUO77/p/5833524.html
總結
以上是生活随笔為你收集整理的【每天一道算法题】Numeric Keypad的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【框架】[Spring]XML配置实现A
- 下一篇: 对datatable操作经验-排序和分页