DuongNhi99

D - Palindromic Numbers (15-12)

Dec 15th, 2020 (edited)
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.53 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define int64_t long long
  3. using namespace std;
  4.  
  5. int L, R;
  6. int digit[50];
  7. int64_t dp[50][50][2];
  8. int num[50];
  9.  
  10. int64_t getNum(int pre, int pos, int start, bool limit) {
  11.     if(pos == -1) return start;
  12.  
  13.     if(dp[pre][pos][start] != -1 && !limit)
  14.         return dp[pre][pos][start];
  15.  
  16.     int64_t ans = 0;
  17.     int up = (limit) ? digit[pos] : 9;
  18.  
  19.     for(int i = 0; i <= up; ++i) {
  20.         num[pos] = i;
  21.         if(pos == pre && i==0)
  22.             ans += getNum(pre-1, pos-1, start, limit && i == up);
  23.         else if(start && pos < (pre + 1)/2)
  24.             ans += getNum(pre, pos-1, num[pre-pos] == i, limit && i == up);
  25.         else
  26.             ans += getNum(pre, pos-1, start, limit && i == up);
  27.     }
  28.  
  29.     if(!limit)
  30.         dp[pre][pos][start] = ans;
  31.  
  32.     return ans;
  33. }
  34.  
  35. int64_t getDigits(int64_t x) {
  36.     int pos = 0;
  37.     while(x) {
  38.         digit[pos++] = x % 10;
  39.         x /= 10;
  40.     }
  41.     return getNum(pos - 1, pos - 1, 1, 1);
  42. }
  43.  
  44. void solve(int Tcase) {
  45.     if(L > R) swap(L, R);
  46.  
  47.     cout << "Case " << Tcase << ": " << getDigits(R) - getDigits(L - 1) << '\n';
  48. }
  49.  
  50. int32_t main() {
  51. #ifdef DN
  52.     freopen("in.txt", "r", stdin);
  53. #endif
  54.     //freopen("D-Palindromic Numbers.inp", "r", stdin);
  55.     //freopen("D-Palindromic Numbers.out", "w", stdout);
  56.     ios_base::sync_with_stdio(false);
  57.     cin.tie(NULL); cout.tie(NULL);
  58.  
  59.     int t; cin >> t;
  60.     memset(dp, -1, sizeof(dp));
  61.     for(int i = 1; i <= t; ++i) {
  62.         cin >> L >> R;
  63.         solve(i);
  64.     }
  65.  
  66.     return 0;
  67. }
  68.  
Add Comment
Please, Sign In to add comment