結果
| 問題 |
No.3 ビットすごろく
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2019-02-24 19:38:02 |
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 3 ms / 5,000 ms |
| コード長 | 1,174 bytes |
| コンパイル時間 | 828 ms |
| コンパイル使用メモリ | 80,268 KB |
| 最終ジャッジ日時 | 2025-01-06 21:45:33 |
|
ジャッジサーバーID (参考情報) |
judge5 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 33 |
ソースコード
#include <iostream>
#include <string>
#include <vector>
#include <deque>
#include <climits>
using namespace std;
int parseInt() {
string line;
getline(std::cin, line);
size_t parsed;
int const N = stoi(line, &parsed);
if (parsed != line.size()) {
cout << "Malformed integer input: " << line << endl;
exit(1);
}
return N;
}
size_t popcnt(int n) {
int i;
for (i = 0; n; ++i) {
n &= n - 1;
}
return i;
}
int main(void) {
int const N = parseInt();
vector<int> dists(N, INT_MAX);
dists[0] = 1;
deque<size_t> q = { 1 };
auto const check = [&](int const next, size_t const new_steps) {
auto index = next - 1;
if (next > 0 && next <= N && new_steps < dists[index]) {
dists[index] = new_steps;
q.push_back(next);
}
};
while (q.size()) {
size_t const val = q.front();
q.pop_front();
auto const new_steps = dists[val - 1] + 1;
if (new_steps > N) {
continue;
}
else if (val == N) {
cout << to_string(dists[val - 1]) << endl;
return 0;
}
size_t const c = popcnt(val);
check(val - c, new_steps);
check(val + c, new_steps);
}
cout << (dists.back() < INT_MAX ? to_string(dists.back()) : "-1") << endl;
return 0;
}