#include #include #include #include #include #include //解説読みました。Orz //幅優先探索は難しいなぁ。 #define Test 0 typedef std::int16_t IntT; typedef std::tuple DType; typedef std::vector Stack; typedef std::vector Stack2; IntT BitCount(const IntT& v) { IntT C =0; for (IntT i = 0; i <= std::numeric_limits::digits; i++) { C += (v&(1 << i)) > 0; } return C; } bool Rec(Stack2& S,const IntT& N,const IntT& V) { IntT B = BitCount(V); if (S.size() == 0) return false; if (V == N) return true; if (V > N)return false; if (V == 0) return false; //auto it = std::find(S.rbegin(), S.rend(), V+B); //if (it != S.rend()) return false; S.push_back(V + B); if (Rec(S, N, V + B) == true) return true; S.pop_back(); auto it = std::find(S.rbegin(), S.rend(), V-B); if (it != S.rend()) return false; S.push_back(V - B); if (Rec(S, N,V - B) == true) return true; S.pop_back(); return false; } /** / IntT MakeHoge_2(const IntT& N) { Stack2 S; S.push_back(1); Rec(S, N,1); return S.back()==N? S.size():0; } /** / std::size_t MakeHoge_1(const IntT& N) { Stack S; IntT C = 1; IntT B = 0; S.push_back(std::make_tuple(C, 0)); while (C != N && S.size() != 0) { if (std::get<1>(S.back()) == 2) { S.pop_back(); continue; } C = std::get<0>(S.back()); B = BitCount(C); if (std::get<1>(S.back()) == 0) { C += B; } else { C -= B; } std::get<1>(S.back())++; auto rit = std::find_if(S.rbegin(), S.rend(), [&](auto& o) {return std::get<0>(o) == C; }); if (rit != S.rend()) { S.erase(rit.base(), S.rbegin().base()); } else { if (C <= N) { S.push_back(std::make_tuple(C, 0)); } } } return S.size(); } /**/ IntT MakeHoge(const IntT& N) { IntT IV = -1; Stack2 S(N+1, IV); IntT Now = 1; bool F = true; IntT B = 0; IntT C = 0; S[1] = 0; while (F) { F = false; for (IntT i = 1; i < S.size(); i++) { if (S[i] == -1) continue; B = BitCount(i); if (i - B > 0 && S[i - B] == -1) { S[i - B] = i; F = true; } if (i + B <= N&& S[i + B] == -1) { S[i + B] = i; F = true; } } } if (S[N] == -1) return -1; Now = N; while (Now != 1) { C++; Now = S[Now]; } return C+1; } /**/ int main() { IntT R = 0; IntT N = 0; #if Test N = 5; R = MakeHoge(N); std::cout << ((R == 0) ? -1 : R) << std::endl; N = 11; R = MakeHoge(N); std::cout << ((R == 0) ? -1 : R) << std::endl; N = 4; R = MakeHoge(N); std::cout << ((R == 0) ? -1 : R) << std::endl; N = 2343; R = MakeHoge(N); std::cout << ((R == 0) ? -1 : R) << std::endl; #else std::cin >> N; R = MakeHoge(N); std::cout << ((R == 0) ? -1 : R) << std::endl; #endif return 0; }