码迷,mamicode.com
首页 > 其他好文 > 详细

ZOJ3816-Generalized Palindromic Number(DFS数位搜索)

时间:2014-09-11 13:55:32      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   strong   for   2014   

Generalized Palindromic Number

Time Limit: 2 Seconds      Memory Limit: 65536 KB

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.

Input

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).

Output

For each test case, output the largest generalized palindromic number less than N.

Sample Input

4
12
123
1224
1122

Sample Output

11
121
1221
1121
题意:找1~N-1中最大的数字(该数字压缩为回文串)
思路:采用数位DP的思想,枚举每一位,左右同时枚举,要从大到小枚举。
#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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!