spoj 5 PALIN
来源:互联网 发布:php集成环境安装包比较 编辑:程序博客网 时间:2024/06/06 00:37
PALIN - The Next Palindrome
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
参考:
将问题分为以下五种情况:
- 如果所给的数全部由 9 组成,则输出 10…01 ,这里 0 的个数比 9 的个数少一个。(第 22 行,第 49 到 53 行的 IsWhole9s 方法,第 29 到 34 行的 Out 方法)
- 否则,如果所给的数只有一位数,则输出下一个数字。(第 23 行)
- 否则,如果所给的数的左半边倒转过来大于右半边,则以左半边为基准输出回文数。(第 24 行,第 55 到 66 行的 IsLeftReverseLargerThanRight 方法,第 36 到 47 行的 Out 方法,第 68 到 73 行的 GetLeftReverse 方法)
- 否则,如果所给的数的位数是奇数,并且最中间一位数字小于 9 ,则将最中间一位数字加一,并以左半边为基准输出回文数。(第 25 行,第 36 到 47 行的 Out 方法)
- 否则,计算所给的数的左半边从低位算起的连续的 9 的个数,这些连续的 9 需要替换为 0 ,然后再将左半边最右侧的非 9 数字加一,以此为基准输出回文数。如果所给的数的位数是奇数,则最中间一位数字必定是 9,这个 9 也必须替换为 0 。(第 26 行,第 75 到 80 行的 GetLeftSuccessive9sCount 方法,第 36 到 47 行的 Out 方法)
除了第一种情况,所求的回文数的位数是和所给的数的位数是一样的。举例如下:
上表中的小数点只是为了标出数的最中间位置,请忽略之。
#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; }
阅读全文
0 0
- spoj 5 PALIN
- SPOJ PALIN
- SPOJ - Palin Square【预处理+枚举】
- 【SPOJ-PALIN】The Next Palindrome【模拟】
- SPOJ
- SPOJ
- SPOJ
- SPOJ
- SPOJ
- SPOJ
- SPOJ
- SPOJ
- SPOJ
- SPOJ
- SPOJ
- SPOJ
- SPOJ
- SPOJ
- JAVA_简单获取用户输入并打印(Scanner scan = new Scanner(S))
- webservice wsdl文件标签讲解
- C++语言为什么跨平台?
- VS工程配置属性设置
- JPA中MySQLSyntaxErrorException问题解决方案
- spoj 5 PALIN
- Pandas用法入门简介
- 解析XML字符串
- 【找规律】UVALive
- Linux性能评测工具之一:gprof篇
- mongoDB基础使用(三)
- Route-Policy 路由策略 实例详解
- 如何快速上手新业务
- Tolua++技术文档