http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=5348
写的真痛苦,换了好几种写法还是不行,贪心贪不对.......
参考了http://www.cnblogs.com/njczy2010/p/3961614.html
思路:
首先枚举左边的每一位,然后枚举右边有几位和这一位相同,写着还是有些细节要注意的
//#pragma comment(linker, "/STACK:102400000,102400000") #include <cstdio> #include <cstring> #include <algorithm> #include <string> #include <iostream> #include <iomanip> #include <cmath> #include <map> #include <set> #include <queue> using namespace std; #define ls(rt) rt*2 #define rs(rt) rt*2+1 #define ll long long #define ull unsigned long long #define rep(i,s,e) for(int i=s;i<e;i++) #define repe(i,s,e) for(int i=s;i<=e;i++) #define CL(a,b) memset(a,b,sizeof(a)) #define IN(s) freopen(s,"r",stdin) #define OUT(s) freopen(s,"w",stdout) const ll ll_INF = ((ull)(-1))>>1; const double EPS = 1e-8; const int INF = 100000000; const int MAXN = 30; ll n; char num[MAXN]; char leftn[MAXN],rightn[MAXN]; int lenn; void init() { sprintf(num,"%lld",n); CL(leftn,0); CL(rightn,0); lenn=strlen(num); for(int i=0;i<lenn;i++) num[i]-='0'; } ll cal(int l, int r) { ll ret=0; for(int i=0;i<l;i++) ret=ret*10+(ll)leftn[i]; for(int i=r-1;i>=0;i--) ret=ret*10+rightn[i]; return ret; } ll dfs(int l, int r, int cur) { //////// /*printf("## l=%d r=%d\n",l,r); for(int i=0;i<l;i++) putchar('0'+i); putchar('\n'); for(int i=r-1;i>=0;i--) putchar('0'+i); putchar('\n');*/ ///////// ll ans=-1; if(l+r>lenn)return -1ll; if(l+r == lenn) { ans=cal(l,r); if(ans>=n)return -1; return ans; } int m= (cur==1) ?num[l]:9; for(int i=m;i>=0;i--) { /// //printf("*******i=%d m=%d\n",i,m); //////// leftn[l]=i; if( ( l==0 || (l>0&&leftn[l]!=leftn[l-1]) ) && !(l==0 && i==0) && (l+r+1!=lenn) )/// { for(int k=1;k+l+r<=lenn;k++)/// { rightn[k+r-1]=i; ans=max(ans, dfs(l+1,r+k,cur&&(m==i))); } } else { ans=max(ans, dfs(l+1, r, cur&&(m==i))); } if(ans>0) return ans; } return ans; } int main() { //IN("H.txt"); int ncase; scanf("%d",&ncase); while(ncase--) { scanf("%lld",&n); init(); printf("%lld\n",dfs(0,0,1)); } return 0; }