v 0. Pasted by slipstak2 as cpp at 2015-01-23 05:35:50 MSK and set expiration to never.

Paste will expire never.

  1. #include <iostream>
  2. #include <string>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6.  
  7. string get_palindrom1(const string &half1) {
  8.     string half2 = half1.substr(0, half1.size() - 1);
  9.     reverse(half2.begin(), half2.end());
  10.     return half1 + half2;
  11.  
  12. }
  13. string get_palindrom2(const string &half1) {
  14.     string half2 = half1;
  15.     reverse(half2.begin(), half2.end());
  16.     return half1 + half2;
  17. }
  18. bool inc(string &half) {
  19.     int carry = 1;
  20.     for (int i = (int)half.size() - 1; i >= 0 && carry; --i) {
  21.         if (half[i] == '9') {
  22.             half[i] = '0';
  23.         } else {
  24.             half[i]++;
  25.             carry = 0;
  26.         }
  27.     }
  28.     if (carry) {
  29.         half = "1" + half;
  30.         return true;
  31.     }
  32.     return false;
  33. }
  34. void normalize(string &str, int len) {
  35.     while (str.size() != len) {
  36.         str += "0";
  37.     }
  38. }
  39. string next_palindr(const string &s) {
  40.     string res;
  41.     string half = s.substr(0, s.size() / 2 + (s.size() % 2));
  42.     string min_palindrom = (s.size() % 2 == 0) ? get_palindrom2(half) : get_palindrom1(half);
  43.     if (min_palindrom > s) {
  44.         res = min_palindrom;
  45.     } else {
  46.         if (!inc(half)) {
  47.             res = (s.size() % 2 == 0) ? get_palindrom2(half) : get_palindrom1(half);
  48.         } else {
  49.             normalize(half, s.size() + 1);
  50.             inc(half);
  51.             res = half;
  52.         }
  53.     }
  54.     return res;
  55. }
  56. int main() {
  57. #ifdef _DEBUG
  58.     freopen("input.txt","r",stdin);
  59.     freopen("output.txt","w",stdout);
  60. #endif
  61.  
  62.     ios_base::sync_with_stdio(false);
  63.     string str;
  64.     cin>>str;
  65.     cout<<next_palindr(str)<<endl;
  66.     return 0;
  67. }


Editing is locked.