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

23 篇文章 0 订阅
7 篇文章 0 订阅

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值