Kattis - palindromicpassword Palindromic Password 求最接近的回文数

The IT department at your school decided to change their password policy. Each password will have to consist of N 6-digit numbers separated by dashes, where N will be determined by the phase of the moon and the weather forecast for the day after it will be generated.

You realized that, if all of the numbers were palindromes (same numbers as the original ones if read backwards), you would have to remember a bunch of 3-digit numbers, which did not sound that bad (at the time).

In order to generate your password of N numbers, you get a list of N randomly generated 6-digit numbers and find the palindromic number closest to them.

Of course, you would like to automate this process...

Input
The first line of the input contains a single positive integer N≤1000 indicating the number of six-digit numbers in the input. Each of the next N lines contains a six-digit number without leading zeroes.

Output
For each six-digit number in the input, output another six-digit number that is closest to it and is also a palindrome. “Closest” in this context means “a number having the smallest absolute difference with the original number”. If there are two different numbers satisfying the above condition, output the smaller one of the two. Remember, no leading zeroes.

Sample Input 1    Sample Output 1
2
123321
123322
123321
123321
题意:长度为6的数字,求最接近他的回文数

思路: 贪心,数字abcdef 取前三位数字abc,然后abc 本身abc+1  abc-1,让这3个回文后减去abcdef。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <map>
#include <set>
#include <cmath>
#include <queue>
const int MAXN=1e6+5;
const int P=99991;
typedef long long ll;
using namespace std;
char s[105];
int a[105];
struct node
{
    int re;
    int num;
    int id;
    int sum;
}c[105];
int cal(int n)
{
    int sum=0;
    while(n){
        sum=sum*10+n%10;
        n=n/10;
    }
    return sum;
}
bool cmp(node a,node b)
{
    if(a.sum!=b.sum)
      return a.sum<b.sum;
    else
      return a.re<b.re;
}
int main()
{
    int t,n;
    scanf("%d",&t);
    while(t--){
       scanf("%s",s);
       int len=strlen(s),sum=0;
       for(int i=0;i<len;i++){
        a[i]=s[i]-'0';
        sum=sum*10+a[i];
       }
        c[1].num=a[0]*100+a[1]*10+a[2];
        c[2].num=c[1].num+1;
        c[3].num=c[1].num-1;
        for(int i=1;i<=3;i++){
            c[i].id=i;
            c[i].re=c[i].num*1000+cal(c[i].num);
            c[i].sum=abs(c[i].re-sum);
        }
        sort(c+1,c+4,cmp);
        printf("%d\n",c[1].re);
       }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/deepseazbw/article/details/81281427