読者です 読者をやめる 読者になる 読者になる

RUPC 2016 Day1 E: 28

競技プログラミング AOJ

コード

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

template <typename T>
std::ostream& operator<<(std::ostream& out, const std::vector<T>& v) {
  if (!v.empty()) {
    out << '[';
    std::copy(v.begin(), v.end(), std::ostream_iterator<T>(out, ", "));
    out << "\b\b]";
  }
  return out;
}

vector<ll> goods;

ll dfs(ll n, ll cnt, ll k) {
  if (n == 1) return cnt;
  if (n % 2 == 1) return -1;
  for (int i = k; i < goods.size(); i++) {
    ll v = goods[i];
    if (v > n) break;
    if (n % v == 0) {
      ll d = dfs(n / v, cnt + 1, i);
      if (d > 0) return d;
    }
  }
  return -1;
}

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);

  ll N;
  cin >> N;
  if (N == 1) {
    cout << -1 << endl;
    return 0;
  }
  queue<ll> que;
  goods.push_back(2);
  goods.push_back(8);
  que.push(2);
  que.push(8);
  ll a = 10;
  while (!que.empty()) {
    ll p = que.front();
    que.pop();
    if (p > N) break;
    while (a < p) a *= 10;
    goods.push_back(a * 2 + p);
    goods.push_back(a * 8 + p);
    que.push(a * 2 + p);
    que.push(a * 8 + p);
  }
  sort(goods.begin(), goods.end());
  // cerr << goods.size() << endl;

  cout << dfs(N, 0, 0) << endl;
}