結果

問題 No.3 ビットすごろく
ユーザー kuramu
提出日時 2016-01-20 13:45:03
言語 Java
(openjdk 23)
結果
AC  
実行時間 108 ms / 5,000 ms
コード長 1,411 bytes
コンパイル時間 2,276 ms
コンパイル使用メモリ 81,420 KB
実行使用メモリ 54,980 KB
最終ジャッジ日時 2024-07-01 07:42:37
合計ジャッジ時間 5,972 ms
ジャッジサーバーID
(参考情報)
judge3 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 33
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Queue;

public class Main {
	public static void main(String[] args) {
	      BufferedReader stdReader =new BufferedReader(new InputStreamReader(System.in));
	      try {
		      int N = Integer.parseInt(stdReader.readLine());
		      int[] c = new int[N+1];
		      int[] dp = new int[N+1];
		      for(int i=1;i<N+1;i++){
		    	  int count = 0;
		    	  String bin = Integer.toBinaryString(i);
		    	  for(int j=0;j<bin.length();j++){
		    		  if((""+bin.charAt(j)).equals("1")) count++;
		    	  }
		    	  c[i] = count;
		      }
		      
		      Queue<Integer> queue = new ArrayDeque<Integer>();
		      queue.add(1);
		      dp[1] = 1;
		      while(!queue.isEmpty()){
		    	  int temp = queue.poll();
		    	  if(temp == N){
		    		  System.out.println(dp[temp]);
		    		  return;
		    	  }
		    	  
		    	  int front = temp + c[temp];
		    	  int back = temp - c[temp];	    	  
		    	  if((0<front && front <=N) &&dp[front] == 0){
		    		 queue.add(front);
		    		 dp[front] = dp[temp] + 1;
		    	  }
		    	  
		    	  if((0<back && back <=N) &&dp[back] == 0){
		    		  queue.add(back);
		    		  dp[back] = dp[temp] + 1;
		    	  }	
		      }
		      System.out.println(-1);
	    	  } catch (IOException e) {
			e.printStackTrace();
	      }
	}	
}
0