結果

問題 No.3 ビットすごろく
ユーザー kaililits
提出日時 2018-05-30 22:56:11
言語 C++14
(gcc 13.3.0 + boost 1.87.0)
結果
WA  
実行時間 -
コード長 1,164 bytes
コンパイル時間 849 ms
コンパイル使用メモリ 85,104 KB
実行使用メモリ 6,948 KB
最終ジャッジ日時 2024-06-30 08:25:21
合計ジャッジ時間 1,994 ms
ジャッジサーバーID
(参考情報)
judge1 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 10 WA * 23
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <algorithm>
#include <bitset>
#include <iostream>
#include <queue>
#include <sstream>
#include <string>
#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);
  for (auto itr = ss.str().begin(); itr != ss.str().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) {
  int cnt = 1;
  queue<int> q;
  q.push(1);
  vector<int> v;
  v.push_back(1);  // 行ったことがある数字を覚えておく
  while (!q.empty()) {
    int tmp = q.front();
    q.pop();
    if (tmp == n) return cnt;
    int forward = count(tmp) + tmp;
    int backward = tmp - count(tmp);
    if (!in(v, forward) && (forward <= n)) {
      q.push(forward);
      v.push_back(forward);
    } else if (!in(v, backward) && (backward > 0)) {
      q.push(backward);
      v.push_back(backward);
    }
    cnt++;
  }
  return -1;
}

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