makrusak

Untitled

Jan 7th, 2014
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. #include <cstdio>
  2. #include <iostream>
  3. #include <algorithm>
  4. #include <vector>
  5. #include <string>
  6. #include <string.h>
  7. #include <queue>
  8. #include <map>
  9. #include <set>
  10. #include <deque>
  11. #include <cmath>
  12. #include <sstream>
  13. #include <stack>
  14. #include <cassert>
  15.  
  16. #define pb push_back
  17. #define mp make_pair
  18. #define sqr(x) (x)*(x)
  19.  
  20. using namespace std;
  21.  
  22. const int MAXN = 200500;
  23.  
  24. int k,n;
  25. char s[MAXN];
  26. int r;
  27.  
  28. int chislo(char x)
  29. {
  30.     if ( isdigit(x) )
  31.         return (int)(x-'0');
  32.         else return 10+(int)(x-'A');
  33. }
  34.  
  35. int main()
  36. {
  37.     freopen("code.in", "r", stdin);
  38.     freopen("code.out", "w", stdout);
  39.     scanf("%d %d%*c", &k, &n);
  40.     scanf("%s", s);
  41.     k--;
  42.     r=-1;
  43.     int l =0;
  44.     //while ( l<n && s[l] == '0')  l++;
  45.     for (int i=n-1; i>=l; i--)
  46.     {
  47.         int t = chislo(s[i]);
  48.         if ( t<k)
  49.         {
  50.             if ( r != -1)
  51.             {
  52.                 t++;
  53.                 sort(s+i+1, s+n);
  54.                 for (int j=i+1; j<n; j++)
  55.                     if ( s[j] != '0' )
  56.                     {
  57.                         r=j;
  58.                         break;
  59.                     }
  60.                 int t2 = chislo(s[r]);
  61.                 t2--;
  62.                 if ( t < 10)
  63.                     s[i] = (char)('0'+t);
  64.                     else
  65.                     {
  66.                         t-=10;
  67.                         s[i] = (char)('A'+t);
  68.                     }
  69.                 if ( t2 < 10)
  70.                     s[r] = (char)('0'+t2);
  71.                     else
  72.                     {
  73.                         t2-=10;
  74.                         s[r] = (char)('A'+t2);
  75.                     }
  76.                 sort(s+i+1, s+n);
  77.                 printf("%s", s);
  78.                 return 0;
  79.             }
  80.         }
  81.         if ( t > 0)
  82.             r = i;
  83.     }
  84.     printf("Impossible");
  85. }
Advertisement
Add Comment
Please, Sign In to add comment