Educational Codeforces Round 39: E. Largest Beautiful Number

time limit per test  1 second
memory limit per test  256 megabytes
input  standard input
output  standard output

Yes, that's another problem with definition of "beautiful" numbers.

Let's call a positive integer x beautiful if its decimal representation without leading zeroes contains even number of digits, and there exists a permutation of this representation which is palindromic. For example, 4242 is a beautiful number, since it contains 4 digits, and there exists a palindromic permutation 2442.

Given a positive integer s, find the largest beautiful number which is less than s.

Input

The first line contains one integer t (1 ≤ t ≤ 105) — the number of testcases you have to solve.

Then t lines follow, each representing one testcase and containing one string which is the decimal representation of number s. It is guaranteed that this string has even length, contains no leading zeroes, and there exists at least one beautiful number less than s.

The sum of lengths of s over all testcases doesn't exceed 2·105.

Output

For each testcase print one line containing the largest beautiful number which is less than s (it is guaranteed that the answer exists).

Example
input
Copy
4
89
88
1000
28923845
output
88
77
99
28923839


题意:如果一个数满足①长度为偶数;②数字0~9都出现偶数次,那么这个数就是美丽的,给你一个n,求出小于n的最大的美丽数字,输入保证有解,答案不能有前导0


从最低位到最高位暴力就行了,对于当前第k位,如果将这个位子上的数字-1,那么后面所有数字都可以随意

考虑贪心,前面所有出现奇数次的数字从小到大依次从低位填到高位,然后中间全部填9(可以证明如果还有空隙,那么空隙也一定刚好有偶数个)填不下去就说明当前不行,然后这个位置上的数字-2继续判直到减到0为止

中间有解就直接输出,还有注意已经暴力到最高位了并且减到了0还不行,就直接输出len-2个9(len为数字n长度)


#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
char str[200005];
int flag[12], temp[12];
int main(void)
{
	int T, n, i, j, k, cnt;
	scanf("%d", &T);
	while(T--)
	{
		scanf("%s", str+1);
		memset(flag, 0, sizeof(flag));
		n = strlen(str+1);
		if(n%2==1)
		{
			for(i=1;i<=n-1;i++)
				printf("9");
			printf("\n");
			continue;
		}
		for(i=1;i<=n;i++)
			flag[str[i]-'0'] ^= 1;
		cnt = 0;
		for(i=n;i>=1;i--)
		{
			if(str[i]=='0')
			{
				flag[str[i]-'0'] ^= 1;
				continue;
			}
			for(k=1;str[i]-k>='0';k++)
			{
				flag[str[i]-'0'] ^= 1;
				flag[str[i]-k-'0'] ^= 1;
				if(i==1 && str[i]-k=='0')
				{
					for(i=1;i<=n-2;i++)
						printf("9");
					puts("");
					goto loop;
				}
				cnt = 0;
				for(j=0;j<=9;j++)
				{
					if(flag[j])
						temp[++cnt] = j;
				}
				if(cnt<=n-i)
				{
					for(j=1;j<=cnt;j++)
						str[n-j+1] = temp[j]+'0';
					for(j=n-cnt;j>=i+1;j--)
						str[j] = '9';
					str[i] = str[i]-k;
					puts(str+1);
					goto loop;
				}
				flag[str[i]-'0'] ^= 1;
				flag[str[i]-k-'0'] ^= 1;
			}
			flag[str[i]-'0'] ^= 1;
		}
		loop:;
	}
}
/*
1
9000
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值