spoj 5 PALIN

来源:互联网 发布:php集成环境安装包比较 编辑:程序博客网 时间:2024/06/06 00:37

PALIN - The Next Palindrome

#ad-hoc-1

A positive integer is called a palindrome if its representation in the decimal system is the same when read from left to right and from right to left. For a given positive integer K of not more than 1000000 digits, write the value of the smallest palindrome larger than K to output. Numbers are always displayed without leading zeros.

Input

The first line contains integer t, the number of test cases. Integers K are given in the next t lines.

Output

For each K, output the smallest palindrome larger than K.

Example

Input:28082133Output:8182222

Warning: large Input/Output data, be careful with certain languages

参考:

将问题分为以下五种情况:

  1. 如果所给的数全部由 9 组成,则输出 10…01 ,这里 0 的个数比 9 的个数少一个。(第 22 行,第 49 到 53 行的 IsWhole9s 方法,第 29 到 34 行的 Out 方法)
  2. 否则,如果所给的数只有一位数,则输出下一个数字。(第 23 行)
  3. 否则,如果所给的数的左半边倒转过来大于右半边,则以左半边为基准输出回文数。(第 24 行,第 55 到 66 行的 IsLeftReverseLargerThanRight 方法,第 36 到 47 行的 Out 方法,第 68 到 73 行的 GetLeftReverse 方法)
  4. 否则,如果所给的数的位数是奇数,并且最中间一位数字小于 9 ,则将最中间一位数字加一,并以左半边为基准输出回文数。(第 25 行,第 36 到 47 行的 Out 方法)
  5. 否则,计算所给的数的左半边从低位算起的连续的 9 的个数,这些连续的 9 需要替换为 0 ,然后再将左半边最右侧的非 9 数字加一,以此为基准输出回文数。如果所给的数的位数是奇数,则最中间一位数字必定是 9,这个 9 也必须替换为 0 。(第 26 行,第 75 到 80 行的 GetLeftSuccessive9sCount 方法,第 36 到 47 行的 Out 方法)

除了第一种情况,所求的回文数的位数是和所给的数的位数是一样的。举例如下:

情况12345输入999.99721.07387561234567123.45645699.996541239456输出1110001821.12387831235321124.42145700.007541240421

上表中的小数点只是为了标出数的最中间位置,请忽略之。

#include <cstdio>  #include <cstring>    const int maxn = 1000005;    int n, num[maxn];  char str[maxn];    inline bool cmp() {      for(int i = 0; i < n; i++)          if(num[i] < str[i] - '0') return 1;          else if(num[i] > str[i] - '0') return 0;      return 1;  }    int main() {      int T; scanf("%d", &T);      while(T--) {          scanf("%s", str); n = strlen(str);          if(n == 1) {              if(str[0] == '9') printf("11\n");              else printf("%c\n", str[0] + 1);              continue;          }            for(int i = n >> 1; i >= 0; i--) num[i] = num[n - i - 1] = str[i] - '0'; num[n] = 0;            if(cmp()) {              int st = n >> 1; num[st]++;              for(int i = st; num[i] > 9; i++) {                  num[i] = 0;                  num[i + 1]++;                  if(i == n - 1) n++;              }              for(int i = 0; i < st; i++) num[i] = num[n - i - 1];          }          for(int i = 0; i < n; i++) printf("%d", num[i]);          printf("\n");      }      return 0;  }  




原创粉丝点击