結果

問題 No.3 ビットすごろく
ユーザー kaililitskaililits
提出日時 2018-05-31 01:00:53
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 42 ms / 5,000 ms
コード長 1,318 bytes
コンパイル時間 886 ms
コンパイル使用メモリ 86,592 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-14 01:01:07
合計ジャッジ時間 2,716 ms
ジャッジサーバーID
(参考情報)
judge11 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,380 KB
testcase_01 AC 2 ms
4,376 KB
testcase_02 AC 2 ms
4,376 KB
testcase_03 AC 5 ms
4,380 KB
testcase_04 AC 3 ms
4,376 KB
testcase_05 AC 14 ms
4,376 KB
testcase_06 AC 6 ms
4,380 KB
testcase_07 AC 4 ms
4,376 KB
testcase_08 AC 11 ms
4,380 KB
testcase_09 AC 22 ms
4,376 KB
testcase_10 AC 30 ms
4,376 KB
testcase_11 AC 20 ms
4,376 KB
testcase_12 AC 15 ms
4,376 KB
testcase_13 AC 5 ms
4,380 KB
testcase_14 AC 28 ms
4,376 KB
testcase_15 AC 40 ms
4,376 KB
testcase_16 AC 34 ms
4,376 KB
testcase_17 AC 39 ms
4,376 KB
testcase_18 AC 5 ms
4,376 KB
testcase_19 AC 41 ms
4,376 KB
testcase_20 AC 3 ms
4,376 KB
testcase_21 AC 1 ms
4,376 KB
testcase_22 AC 28 ms
4,376 KB
testcase_23 AC 42 ms
4,376 KB
testcase_24 AC 42 ms
4,380 KB
testcase_25 AC 40 ms
4,376 KB
testcase_26 AC 1 ms
4,376 KB
testcase_27 AC 5 ms
4,376 KB
testcase_28 AC 35 ms
4,376 KB
testcase_29 AC 20 ms
4,376 KB
testcase_30 AC 1 ms
4,376 KB
testcase_31 AC 1 ms
4,376 KB
testcase_32 AC 17 ms
4,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <algorithm>
#include <bitset>
#include <iostream>
#include <queue>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
using namespace std;

int dist(int x, int y) { return (x > y) ? (x - y) : (y - x); }

int count(int n) {
  int cnt = 0;
  stringstream ss;
  ss << static_cast<bitset<16> >(n);
  string s = ss.str();
  for (auto itr = s.begin(); itr != s.end(); itr++) {
    if (*itr == '1') cnt++;
  }
  return cnt;
}

bool in(vector<int> v, int n) {
  for (auto& var : v) {
    if (var == n) return true;
  }
  return false;
}

int solve(int n) {
  queue<pair<int, int> > q;  // <位置, 歩数>
  q.push(make_pair(1, 1));
  vector<int> v;
  v.push_back(1);  // 行ったことがある数字を覚えておく
  while (!q.empty()) {
    pair<int, int> tmp = q.front();
    int num = tmp.first;
    int cnt = tmp.second;
    q.pop();
    if (num == n) return cnt;
    int forward = num + count(num);
    int backward = num - count(num);
    if (!(in(v, forward)) && (forward <= n)) {
      q.push(make_pair(forward, cnt + 1));
      v.push_back(forward);
    }
    if (!(in(v, backward)) && (backward > 0)) {
      q.push(make_pair(backward, cnt + 1));
      v.push_back(backward);
    }
  }
  return -1;
}

int main() {
  int n;
  cin >> n;
  cout << solve(n) << endl;
  return 0;
}
0