結果

問題 No.3 ビットすごろく
ユーザー snipsnipsnip
提出日時 2016-05-16 22:09:40
言語 Java
(openjdk 23)
結果
WA  
実行時間 -
コード長 1,209 bytes
コンパイル時間 2,395 ms
コンパイル使用メモリ 77,448 KB
実行使用メモリ 54,560 KB
最終ジャッジ日時 2024-10-06 04:55:57
合計ジャッジ時間 7,046 ms
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 32 WA * 1
権限があれば一括ダウンロードができます

ソースコード

diff #

public class Main {
  public static void main(String[] args) {
    int n = new java.util.Scanner(System.in).nextInt();
    new Main(n).solve();
  }

  private int n;

  Main(int n) {
    this.n = n;
  }

  void solve() {
    System.out.println(path(n));
  }

  int bits(int n) {
    int c = 0;
    while (n > 0) {
      c += n % 2;
      n /= 2;
    }
    return c;
  }

  int path(int n) {
    boolean[] visited = new boolean[n];
    int len = 64;
    short[] q = new short[len];
    short[] depth = new short[len];
    int head = 0;
    int tail = 0;

    q[0] = 1;
    depth[0] = 1;
    tail++;

    while (head != tail) {
      short h = q[head];
      short d = depth[head];
      head = (head + 1) % len;
      if (h == n) { return depth[head]; }
      if (h < 1 || n < h || visited[h - 1]) { continue; }

      visited[h - 1] = true;

      int b = bits(h);

      q[tail] = (short)(h + b);
      depth[tail] = (short)(d + 1);
      tail = (tail + 1) % len;
      if (head == tail) { throw new RuntimeException(); }

      q[tail] = (short)(h - b);
      depth[tail] = (short)(d + 1);
      tail = (tail + 1) % len;
      if (head == tail) { throw new RuntimeException(); }
    }

    return -1;
  }
}
0