hihoCoder week 85 Numeric Keypad 【DFS】

来源:互联网 发布:java quartz 编辑:程序博客网 时间:2024/06/06 08:53

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 34 5 67 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
32583131
Sample Output
2580129

题意:给你一个手机键盘,然后我们在手机上输入数字,即当按下一个键之后,只能把手指向下或者向右移动。开始时手指放在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;}



0 0