結果

問題 No.3 ビットすごろく
ユーザー tenman
提出日時 2017-09-04 22:59:31
言語 C++11(廃止可能性あり)
(gcc 13.3.0)
結果
AC  
実行時間 2 ms / 5,000 ms
コード長 894 bytes
コンパイル時間 593 ms
コンパイル使用メモリ 64,376 KB
実行使用メモリ 6,948 KB
最終ジャッジ日時 2024-07-01 08:48:36
合計ジャッジ時間 1,551 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 33
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <queue>
using namespace std;

const int MAX = 1e4 + 10;
int N;
int d[MAX];

// 10進法の整数を2進法で表したときの1の個数を数える
int bit_digit(int n) {
  int res = 0;
  for (int i = 1; i < (1 << 16); i <<= 1) {
    res += ((n & i) ? 1 : 0);
  }

  return res;
}

// 幅優先探索
int bfs(int n) {
  queue<int> q;
  q.push(n);
  int pos;
  d[1] = 1;

  while (!q.empty()) {
    pos = q.front();
    q.pop();
    if (pos == N) return d[pos];

    int cnt = bit_digit(pos);
    if (pos - cnt >= 1) {
      if (!d[pos-cnt]) {
        d[pos-cnt] = d[pos] + 1;
        q.push(pos - cnt);
      }
    }
    if (pos + cnt <= N) {
      if (!d[pos+cnt]) {
        d[pos+cnt] = d[pos] + 1;
        q.push(pos + cnt);
      }
    }
  }

  return -1;
}

int main() {
  // 入力
  cin >> N;

  // 幅優先探索
  cout << bfs(1) << endl;

  return 0;
}
0