标签:style blog color io os ar strong for 2014
A number that will be the same when it is written forwards or backwards is known as a palindromic number. For example, 1234321 is a palindromic number.
We call a number generalized palindromic number, if after merging all the consecutive same digits, the resulting number is a palindromic number. For example, 122111 is a generalized palindromic number. Because after merging, 122111 turns into 121 which is a palindromic number.
Now you are given a positive integer N, please find the largest generalized palindromic number less than N.
There are multiple test cases. The first line of input contains an integer T (about 5000) indicating the number of test cases. For each test case:
There is only one integer N (1 <= N <= 1018).
For each test case, output the largest generalized palindromic number less than N.
4 12 123 1224 1122
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <string> #include <map> #include <stack> #include <vector> #include <set> #include <queue> #define maxn 401 #define MAXN 200005 #define INF 0x3f3f3f3f #define mod 1000000007 #define eps 1e-6 const double pi=acos(-1.0); typedef long long ll; using namespace std; ll n,m,ans; int tot,dig[20],le[20],ri[20]; ll get(int num1,int num2) { int i; ll res=0; for(i=1;i<=num1;i++) { res=res*10+le[i]; } for(i=num2;i>=1;i--) { res=res*10+ri[i]; } return res; } ll dfs(int num1,int num2,int limit) { ll t,res=0; if(num1+num2>tot) { res=get(num1-1,num2); if(res<m) return res; return 0; } int i,j,ed; ed=limit?dig[tot-num1+1]:9; for(i=ed;i>=0;i--) { le[num1]=i; if((num1==1||le[num1]!=le[num1-1])&&!(num1==1&&i==0)&&(num1+num2<tot)) { for(j=1; num1+num2+j<=tot; j++) // r与之匹配的个数 { ri[num2+j]=i; t=dfs(num1+1,num2+j,limit&&(i==ed)); res=max(res,t); } } else { t=dfs(num1+1,num2,limit&&(i==ed)); res=max(res,t); } if(res>0) return res; } return res; } void solve() { int i,j; tot=0; m=n; while(n) { dig[++tot]=n%10; n/=10; } ans=dfs(1,0,1); printf("%lld\n",ans); } int main() { int i,j,t; scanf("%d",&t); while(t--) { scanf("%lld",&n); solve(); } return 0; }
zoj 3816 Generalized Palindromic Number (根据对称性来搜)
标签:style blog color io os ar strong for 2014
原文地址:http://blog.csdn.net/tobewhatyouwanttobe/article/details/39227223