結果

問題 No.3 ビットすごろく
ユーザー 37zigen37zigen
提出日時 2016-04-27 17:10:15
言語 Java
(openjdk 23)
結果
AC  
実行時間 162 ms / 5,000 ms
コード長 1,035 bytes
コンパイル時間 2,306 ms
コンパイル使用メモリ 78,424 KB
実行使用メモリ 54,528 KB
最終ジャッジ日時 2024-07-01 07:50:15
合計ジャッジ時間 8,364 ms
ジャッジサーバーID
(参考情報)
judge2 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 33
権限があれば一括ダウンロードができます

ソースコード

diff #

package yukicoder;
import java.util.*;
public class Main {
	public static void main(String[] args)throws Exception{
		new Main().solve();
	}
	void solve(){
		Scanner sc=new Scanner(System.in);
		int n=sc.nextInt();
		if(n==1){
			System.out.println(1);
			return;
		}
		boolean[] arrived=new boolean[n+1];
		Arrays.fill(arrived, false);
		ArrayDeque<P> que=new ArrayDeque<P>();
		que.add(new P(1,1));
		arrived[1]=true;
		while(!que.isEmpty()){
			P p=que.poll();
			int c=count_1(p.n);
			int[] a=new int[2];
			a[0]=p.n+c;
			a[1]=p.n-c;
			for(int i=0;i<2;i++){
				if(a[i]>n||a[i]<=0)continue;
				if(arrived[a[i]]==true)continue;
				if(a[i]==n){
					System.out.println(p.c+1);
					return;
				}
				que.add(new P(a[i],p.c+1));	
				arrived[a[i]]=true;
			}
		}
		System.out.println(-1);
	}
	class P{
		int n;
		int c;
		P(int n,int c){
			this.n=n;
			this.c=c;
		}
	}
	int count_1(int n){
		String str=Integer.toBinaryString(n);
		int c=0;
		for(int i=0;i<str.length();i++){
			if(str.charAt(i)=='1')c++;
		}
		return c;
	}
}
0