結果

問題 No.3 ビットすごろく
ユーザー wikeakawikeaka
提出日時 2016-09-17 16:32:08
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 505 ms / 5,000 ms
コード長 1,520 bytes
コンパイル時間 652 ms
コンパイル使用メモリ 73,020 KB
実行使用メモリ 4,384 KB
最終ジャッジ日時 2023-09-14 00:08:30
合計ジャッジ時間 7,578 ms
ジャッジサーバーID
(参考情報)
judge15 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,380 KB
testcase_01 AC 2 ms
4,380 KB
testcase_02 AC 2 ms
4,380 KB
testcase_03 AC 30 ms
4,376 KB
testcase_04 AC 4 ms
4,384 KB
testcase_05 AC 144 ms
4,380 KB
testcase_06 AC 36 ms
4,380 KB
testcase_07 AC 12 ms
4,376 KB
testcase_08 AC 79 ms
4,380 KB
testcase_09 AC 210 ms
4,376 KB
testcase_10 AC 298 ms
4,380 KB
testcase_11 AC 175 ms
4,376 KB
testcase_12 AC 135 ms
4,376 KB
testcase_13 AC 22 ms
4,376 KB
testcase_14 AC 319 ms
4,376 KB
testcase_15 AC 494 ms
4,376 KB
testcase_16 AC 371 ms
4,380 KB
testcase_17 AC 421 ms
4,376 KB
testcase_18 AC 15 ms
4,380 KB
testcase_19 AC 442 ms
4,376 KB
testcase_20 AC 2 ms
4,376 KB
testcase_21 AC 1 ms
4,380 KB
testcase_22 AC 328 ms
4,376 KB
testcase_23 AC 505 ms
4,376 KB
testcase_24 AC 443 ms
4,380 KB
testcase_25 AC 433 ms
4,376 KB
testcase_26 AC 2 ms
4,376 KB
testcase_27 AC 23 ms
4,380 KB
testcase_28 AC 357 ms
4,376 KB
testcase_29 AC 182 ms
4,380 KB
testcase_30 AC 2 ms
4,376 KB
testcase_31 AC 1 ms
4,380 KB
testcase_32 AC 155 ms
4,380 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <algorithm>
#include <vector>
#include <bitset>
#include <limits>
#include <numeric>

using namespace std;


using Vertex = int;
using Edge = pair<int, int>;
using Graph = pair<vector<Vertex>, vector<Edge>>;

int step(const int x) {
  const int BIT_MAX = 14;
  bitset<BIT_MAX> bs(x);
  return bs.count();
}

vector<Edge> makeEdges(const int N) {
  vector<Edge> e;

  for (int i=0; i<N; ++i) {
    int s = step(i+1);
    if (0 <= i-s && i-s < N) e.push_back(Edge(i, i-s));
    if (0 <= i+s && i+s < N) e.push_back(Edge(i, i+s));
  }
  return e;
}

int dijkstra(const vector<Edge> e, const int start, const int goal) {
  vector<float> costs(goal - start + 1, numeric_limits<float>::infinity());
  costs[start] = 0;
  vector<int> t(goal - start + 1);
  iota(t.begin(), t.end(), 0);

  int min_v = start;
  while (min_v != goal) {
    for (auto x : e) {
      if (x.first != min_v) continue;
      if (find(t.begin(), t.end(), x.second) == t.end()) continue;
      if (costs[x.second] > costs[x.first] + 1) costs[x.second] = costs[x.first] + 1;
    }

    t.erase(remove(t.begin(), t.end(), min_v));

    min_v = t[0];
    for (auto x : t) {
      if (costs[min_v] > costs[x]) min_v = x;
    }
  }
  if (costs[goal] == numeric_limits<float>::infinity()) return -1;
  return costs[goal];
}

int main() {
  int N;
  cin >> N;

  const vector<Edge> e = makeEdges(N);
  int answer = dijkstra(e, 0, N-1);
  if (answer < 0)
    cout << -1;
  else
    cout << answer + 1;
  cout << endl;
  return 0;
}
0