結果

問題 No.3 ビットすごろく
ユーザー uafr_cs
提出日時 2015-05-29 01:02:30
言語 Java
(openjdk 23)
結果
AC  
実行時間 145 ms / 5,000 ms
コード長 935 bytes
コンパイル時間 2,208 ms
コンパイル使用メモリ 78,456 KB
実行使用メモリ 42,316 KB
最終ジャッジ日時 2024-07-01 07:23:07
合計ジャッジ時間 8,110 ms
ジャッジサーバーID
(参考情報)
judge2 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 33
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {
	
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		
		final int N = sc.nextInt();
		
		int[] min_costs = new int[N + 1];
		Arrays.fill(min_costs, Integer.MAX_VALUE);
		min_costs[1] = 1;
		
		Queue<Integer> queue = new LinkedList<Integer>();
		queue.add(1);
		
		while(!queue.isEmpty()){
			final int pos = queue.poll();
			final int pops = Integer.bitCount(pos);
			
			
			for(int move : new int[]{-pops, pops}){
				final int next_pos = pos + move;
				
				if(next_pos < 1 || next_pos > N){
					continue;
				}else if(min_costs[next_pos] <= min_costs[pos] + 1){
					continue;
				}else{
					min_costs[next_pos] = min_costs[pos] + 1;
					queue.add(next_pos);
				}
				
			}
		}
		
		System.out.println(min_costs[N] == Integer.MAX_VALUE ? -1 : min_costs[N]);
		
		
	}
	
}
0