結果
| 問題 | No.3 ビットすごろく | 
| コンテスト | |
| ユーザー |  | 
| 提出日時 | 2018-04-16 13:23:14 | 
| 言語 | Java (openjdk 23) | 
| 結果 | 
                                AC
                                 
                             | 
| 実行時間 | 147 ms / 5,000 ms | 
| コード長 | 1,430 bytes | 
| コンパイル時間 | 2,206 ms | 
| コンパイル使用メモリ | 78,016 KB | 
| 実行使用メモリ | 54,832 KB | 
| 最終ジャッジ日時 | 2024-07-01 08:58:51 | 
| 合計ジャッジ時間 | 7,932 ms | 
| ジャッジサーバーID (参考情報) | judge3 / judge4 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| other | AC * 33 | 
ソースコード
import java.io.*;
import java.util.*;
class Main{
  public static void main(String[] args) throws IOException{
    Scanner scan=new Scanner(System.in);
    int n=scan.nextInt();
    if(n==1){
      System.out.println(1);
      return;
    }
    Queue<Integer> queue=new ArrayDeque<Integer>();//空のキュー
    int[] dist=new int[n+1];//訪問したかどうかの判別する配列
    Arrays.fill(dist,Integer.MAX_VALUE);//初期化
    queue.offer(1);//キューに最初の1のマスを格納する
    dist[1]=1;//1のマスを訪問済みにする
    while(!queue.isEmpty()){
      int now=queue.poll();
      int bit=f(now);//bitが立っている数を数える
      //探索が完了したら出力して終了
      if(now+bit==n){
        System.out.println(dist[now]+1);
        return;
      }
      //未訪問で左に移動できる場合
      if(now-bit>0 && dist[now-bit]==Integer.MAX_VALUE){
        dist[now-bit]=dist[now]+1;
        queue.offer(now-bit);
      }
      //未訪問で右に移動できる場合
      if(now+bit<n && dist[now+bit]==Integer.MAX_VALUE){
        dist[now+bit]=dist[now]+1;//次のマスを訪問済みにする
        queue.offer(now+bit);//次のマスをキューに格納する
      }
    }
    System.out.println(-1);
  }
  static int f(int x){
    int count=0;
    while(x>0){
      if(x%2==1){
        count++;
      }
      x/=2;
    }
    return count;
  }
}
            
            
            
        