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

ZOJ - 3816 Generalized Palindromic Number

时间:2014-09-07 22:31:15      阅读:241      评论:0      收藏:0      [点我收藏+]

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

Description

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
题意:求小于N的回文数,这个数的回文相同的数可以缩成一个数
思路:dfs(l, r, eq):l代表左边侧长度,r代表右边的长度,eq代表是否处于边界,然后在搜索右边匹配左边的同时,枚举k,k代表连续相同的数都匹配左边的个数
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
typedef long long ll;
using namespace std;

char str[50];
int len;
char leftnum[50], rightnum[50];
char ans[50];
ll target;

ll getans(int l, int r) {
	ll ans = 0;
	for (int i = 1; i <= l; i++)
		ans = ans * 10 + leftnum[i];
	for (int i = r; i >= 1; i--)
		ans = ans * 10 + rightnum[i];
	return ans;
}
ll dfs(int l, int r, int eq) {
	ll ans = -1;
	if (l + r - 1 >= len) {
		if (l + r - 1 > len)
			return -1ll;
		ans = getans(l - 1, r);
		if (ans < target)
			return ans;
		return -1ll;
	}

	int m = eq ? str[l] : 9;
	for (int i = m; i >= 0; i--) {
		leftnum[l] = i;
		if ((l == 1 || leftnum[l] != leftnum[l - 1]) && !(l == 1 && i == 0) && !(l+r == len)) {
			for (int k = 1; k + r + l <= len; k++) {
				rightnum[r + k] = i;
				ans = max(ans, dfs(l + 1, r + k, eq && (i == m)));
			}
		}
		else ans = max(ans, dfs(l + 1, r, eq && i == m));
		if (ans  > 0 )
			return ans;
	}
	return ans;
}

int main() {
	int t;
	scanf("%d", &t);
	while (t--) {
		scanf("%lld", &target);
		sprintf(str+1, "%lld", target);
		len = strlen(str+1);
		for (int i = 1; i <= len; i++)
			str[i] -= '0';
		printf("%lld\n", dfs(1, 0, 1));
	}
	return 0;
}


ZOJ - 3816 Generalized Palindromic Number

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

原文地址:http://blog.csdn.net/u011345136/article/details/39122741

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