Advertisement
leoanjos

Enigma

Oct 14th, 2021
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.11 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. #define long long long int
  6.  
  7. int N;
  8. string S;
  9. vector<vector<int>> memo;
  10.  
  11. long exp(int a, int e) {
  12.     if (!e) return 1LL;
  13.  
  14.     long ans = exp(a, e >> 1);
  15.     ans = (ans * ans) % N;
  16.  
  17.     if (!(e & 1)) return ans;
  18.     return (ans * a) % N;
  19. }
  20.  
  21. bool possible(int i = 0, int rem = 0) {
  22.     if (i >= (int) S.size()) return !rem;
  23.  
  24.     int &ans = memo[i][rem];
  25.     if (~ans) return ans;
  26.  
  27.     long pot = exp(10, (int) S.size() - i - 1);
  28.     if (S[i] >= '0' && S[i] <= '9') {
  29.         int d = S[i] - '0';
  30.         int aux = (d * pot) % N;
  31.         return ans = possible(i + 1, (rem + aux) % N);
  32.     }
  33.  
  34.     for (int j = !i ? 1 : 0; j < 10; j++) {
  35.         int aux = (j * pot) % N;
  36.         if (possible(i + 1, (rem + aux) % N)) {
  37.             S[i] = '0' + j;
  38.             return ans = true;
  39.         }
  40.     }
  41.  
  42.     return ans = false;
  43. }
  44.  
  45. int main() {
  46.     ios_base::sync_with_stdio(false);
  47.     cin.tie(NULL);
  48.  
  49.     cin >> S >> N;
  50.  
  51.     memo.assign((int) S.size() + 5, vector<int>(N + 5, -1));
  52.  
  53.     if (!possible()) cout << "*\n";
  54.     else cout << S << "\n";
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement