ZOJ - 3816 Generalized Palindromic Number

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;
}


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值