您的位置:首页 > 其它

hihoCoder week 85 Numeric Keypad 【DFS】

2016-02-20 18:19 537 查看


P1 : Numeric Keypad

Time Limit:10000ms
Case Time Limit:1000ms
Memory Limit:256MB


Description

The numberic keypad on your mobile phone looks like below:
1 2 3
4 5 6
7 8 9
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) move your 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.


Input

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 <= 10500, t <= 20.


Output

For each testcase output one line, the maximum number less than or equal to the corresponding K that can be produced.

Sample Input
3
25
83
131


Sample Output
25
80
129


题意:给你一个手机键盘,然后我们在手机上输入数字,即当按下一个键之后,只能把手指向下或者向右移动。开始时手指放在1上。问通过这种特殊方式输入的最大不超过S的数字是多少。

思路:DFS 从高位扫一遍,每次选尽可能大的数去填。

AC代码:

#include <iostream>
#include <string>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#define CLR(a, b) memset(a, (b), sizeof(a))
#define PI acos(-1.0)
using namespace std;
typedef long long LL;
typedef double DD;
bool g[10][10] =
{
1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 0, 1, 1, 0, 1, 1, 0, 1, 1,
0, 0, 0, 1, 0, 0, 1, 0, 0, 1,
1, 0, 0, 0, 1, 1, 1, 1, 1, 1,
1, 0, 0, 0, 0, 1, 1, 0, 1, 1,
0, 0, 0, 0, 0, 0, 1, 0, 0, 1,
1, 0, 0, 0, 0, 0, 0, 1, 1, 1,
1, 0, 0, 0, 0, 0, 0, 0, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
};
string str;
int ans[502];
bool DFS(int len, int lastval, int bit, bool yes)
{
if(bit == len) return true;
if(yes)
{
for(int i = bit; i < len; i++)
ans[i] = lastval ? 9 : 0;
return true;
}
int v = str[bit] - '0';
for(int i = 9; i >= 0; i--)
{
if(g[lastval][i] && i <= v)
{
ans[bit] = i;
if(DFS(len, i, bit+1, yes|i < v)) return true;
}
}
return false;
}
int main()
{
int t; cin >> t;
while(t--)
{
cin >> str;
int len = str.size();
DFS(len, 1, 0, false);
for(int i = 0; i < len; i++) cout << ans[i];
cout << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: