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; }