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.

IDEA

1.首先确定从一个数字digit1能否到达另一个数字digit2,能够到达需要满足:digit2(x2,y2)在digit1(x1,y1)的右下方,即x1<=x2,y1<=y2

2.输入的数从左到右检查两个相邻的数字能否到达,i->i+1位

如果能够到达,则继续检查下一位

如果不能达到,i+1的数字减一,再检查能否到达...

若果i+1减到负数,则第i位数字减一,并回溯一位,将i指向前一位(i--),将后几位都置为9

在进行检查

CODE

#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
void locate(int digit,int &x,int &y){
	digit=digit?--digit:10;
	x=digit/3;
	y=digit%3;
}
int reach(int digit1,int digit2){
	int x1,y1;
	int x2,y2;
	locate(digit1-'0',x1,y1);
	locate(digit2-'0',x2,y2);
	return x1<=x2&&y1<=y2;
}
int main(){
	#ifndef ONLINE_JUDGE
	freopen("input.txt","r",stdin);
	#endif 
	int n;
	cin>>n;
	while(n--){
		string str;
		cin>>str;
		for(int i=0;i<str.size()-1;i++){
			while(!reach(str[i],str[i+1])){
				str[i+1]--;
				if(str[i+1]<0){
					str[i]--;
					i--;
				}
				for(int j=i+2;j<str.length();j++){
					str[j]='9';
				}
			}
		}
		cout<<str<<endl;
	} 
	return 0;
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值