結果

問題 No.3 ビットすごろく
ユーザー FpmpAmpm
提出日時 2016-10-23 00:00:05
言語 Java
(openjdk 23)
結果
AC  
実行時間 144 ms / 5,000 ms
コード長 1,626 bytes
コンパイル時間 2,213 ms
コンパイル使用メモリ 77,720 KB
実行使用メモリ 54,220 KB
最終ジャッジ日時 2024-07-01 08:07:45
合計ジャッジ時間 7,922 ms
ジャッジサーバーID
(参考情報)
judge4 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 33
権限があれば一括ダウンロードができます

ソースコード

diff #


import java.util.Queue;
import java.util.Scanner;
import java.util.ArrayDeque;

class que2 {
    public static void main(String[] args){
        
    	Scanner sc = new Scanner(System.in);
    	int N = sc.nextInt();
    	sc.close();
    	//int N = 4179;
    	int[] visited = new int[N];
    	
    	Queue<Node> queue = new ArrayDeque<>();
        queue.add(new Node(1,1));
        while(true){
        	// 中身取り出しはpoll
            Node n = queue.poll();
            if (n == null) break;
            // ゴール判定
            if (n.currentPosition == N) {
            	System.out.println(n.count);
            	return;
            }
            // 移動先が存在する場合キューに詰める
    		// 前に存在
    		if (n.currentPosition + n.getBitCount() < N + 1 && visited[n.currentPosition + n.getBitCount() - 1] == 0) {
    			visited[n.currentPosition + n.getBitCount() - 1] = n.count;
    			queue.add(new Node((n.currentPosition + n.getBitCount()), n.count + 1));
    		}
    		// 後ろに存在
    		if (1 < n.currentPosition - n.getBitCount() && visited[n.currentPosition - n.getBitCount() - 1] == 0) {
    			visited[n.currentPosition - n.getBitCount() - 1] = n.count;
    			queue.add(new Node(n.currentPosition - n.getBitCount(), n.count + 1));
    		}    
        }
        // ゴールにたどり着かずに探索ノードが尽きた
        System.out.println(-1);
    }
}   
class Node{
	int count;
	int currentPosition;
	public Node(int i, int c) {
		this.currentPosition = i;
		this.count = c;
	}
	public int getBitCount() {
		return Integer.bitCount(currentPosition);
	}
}
0