Facebook
From answer, 1 Month ago, written in C++.
Embed
Download Paste or View Raw
Hits: 202
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. typedef long long ll;
  4. int cnt=0;
  5. ll addone(ll n) {
  6.     ll res = 0;
  7.     ll carry = 0;            
  8.     ll factor = 1;          
  9.  
  10.     if (n == 0) return 1;
  11.  
  12.     while (n > 0 || carry > 0) {
  13.         ll digit = n % 10 + 1 + carry;
  14.         carry = digit / 10;                  
  15.         digit %= 10;                        
  16.        
  17.         res += digit * factor;
  18.         factor *= 10;                        
  19.         n /= 10;                            
  20.     }
  21.     //cout<<"=="<<res<<endl;
  22.     return res;
  23. }
  24.  
  25. bool judge(ll n, ll m) {
  26.     if (n == m) return true;
  27.     unordered_set<ll> visited;
  28.     queue<int> q;
  29.     q.push(n);
  30.     visited.insert(n);
  31.  
  32.     for (int i = 0; i < 32 && !q.empty(); ++i) {
  33.         int levelSize = q.size();
  34.         for (int j = 0; j < levelSize; ++j) {
  35.             int curr = q.front();
  36.             q.pop();
  37.             vector<ll> nextNums = {addone(curr), curr / 2};
  38.             for (ll next : nextNums) {
  39.                 if (next == m) return true;
  40.                 if (visited.find(next) == visited.end()) {
  41.                     q.push(next);
  42.                     visited.insert(next);
  43.                 }
  44.             }
  45.         }
  46.     }
  47.     return false;
  48. }
  49.  
  50. int main(){
  51.     ll n, q;
  52.     cin >> n >> q;
  53.     for(int i = 0; i < q; i++){
  54.         ll m;
  55.         cin >> m;
  56.         cnt = 0;
  57.         if(judge(n, m) == true) cout << "YES" << endl;
  58.         else cout << "NO" << endl;
  59.     }
  60.     return 0;
  61. }