标签: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
11 121 1221 1121
#include <iostream> #include <cstdio> #include <cstring> #include <vector> #include <algorithm> using namespace std; typedef long long LL; const int maxn = 20; int lft[maxn],rgt[maxn]; vector<int> digit; LL n,ans; int len; LL getS(int L,int R) { LL ret = 0; for(int i = 0; i < L; i++){ ret *= 10; ret += lft[i]; } for(int i = R; i >= 1; i--) { ret *= 10; ret += rgt[i]; } return ret; } LL dfs(int L,int R,bool done) { if(L+R == len) { LL tmp = getS(L,R); if(tmp <= n-1) return tmp; else return 0; } int end = done?digit[L]:9; LL ans = 0; for(int i = end; i >= 0; i--) { lft[L] = i; if(L+R!=len-1&&(L==0||(L>=1&&lft[L]!=lft[L-1]))&&(L!=0||i!=0)){ for(int k = 1; L+R+k <= len-1; k++) { rgt[k+R] = i; ans = max(dfs(L+1,R+k,done&&i==end),ans); } }else{ ans = max(dfs(L+1,R,done&&i==end),ans); } if(ans != 0) return ans; } return 0; } void init() { ans = 0; digit.clear(); scanf("%lld",&n); LL x = n; --x; while(x) { digit.push_back(x%10); x /= 10; } len = digit.size(); reverse(digit.begin(),digit.end()); } void solve() { ans = dfs(0,0,true); printf("%lld\n",ans); } int main() { int ncase; cin >> ncase; while(ncase--) { init(); solve(); } return 0; }
ZOJ3816-Generalized Palindromic Number(DFS数位搜索)
标签:style blog color io os ar strong for 2014
原文地址:http://blog.csdn.net/mowayao/article/details/39205263