题目:
A palindrome number is a number that can be read the same way from left to right and from right to left. For example: 961169, 111, 554455 are palindromes, while 856, 10180, 7226 are not.
Find the largest palindrome number that satisfies the following rules:
The number of its digits is equal to n, and must not contain leading zeros.
The sum of its digits is equal to s.
If there is no such number print - 1.
Input
The first line of the input contains an integer T (1 ≤ T ≤ 500), where T is the number of the test cases.
Each test case has one line that contains two integers n (1 ≤ n ≤ 106) number of digits, and s (1 ≤ s ≤ 9 × 106) sum of digits.
Output
For each test case, print a single integer that represents the largest palindrome number that satisfies the mentioned rules, if there is no such number print - 1.
Example
Input
2
2 2
4 26
Output
11
9449
题意: 每组输入一个n和s,n代表n位数,s代表每一位数的和,求满足n和s的最大回文数,没有就输出-1;
思路: 把每一位都赋值为9,然后从中间往两边减,有个特例,就是当n和s都为奇数时,最中间那位只要减到1就行了,不能减到0,不然此时的s必然是偶数,不符合。
代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <stdlib.h>
using namespace std;
const int maxn =1000000+5;
int a[maxn];
int main()
{
int T,n,s,sum;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&s);
if((n%2==0&&s%2==1)||(9*n<s)||(n%2==1&&n>1&&s==1))
{
printf("-1\n");
continue;
}
sum=n*9-s;
for(int i=1; i<=n; i++)
{
a[i]=9;
}
int l,r,mid;
if(n%2==0)
{
l=(1+n)/2;
r=(1+n)/2+1;
while(sum)
{
a[l]-=1;
a[r]-=1;
sum-=2;
if(a[l]==0&&a[r]==0)
{
l--;
r++;
}
}
}
else if(n%2==1)
{
mid=(1+n)/2;
while(sum)
{
if(s%2==0)
{
if(a[mid]==0)
break;
a[mid]--;
sum--;
}
else if(s%2==1)
{
if(a[mid]==1)
break;
a[mid]--;
sum--;
}
}
l=mid-1;
r=mid+1;
while(sum)
{
a[l]-=1;
a[r]-=1;
sum-=2;
if(a[l]==0&&a[r]==0)
{
l--;
r++;
}
}
}
for(int i=1; i<=n; i++)
printf("%d",a[i]);
printf("\n");
}
return 0;
}