結果
| 問題 | No.3 ビットすごろく | 
| コンテスト | |
| ユーザー |  ぴろず | 
| 提出日時 | 2014-12-21 01:02:09 | 
| 言語 | Java (openjdk 23) | 
| 結果 | 
                                AC
                                 
                             | 
| 実行時間 | 157 ms / 5,000 ms | 
| コード長 | 1,583 bytes | 
| コンパイル時間 | 2,267 ms | 
| コンパイル使用メモリ | 79,220 KB | 
| 実行使用メモリ | 56,356 KB | 
| 最終ジャッジ日時 | 2024-07-01 07:09:53 | 
| 合計ジャッジ時間 | 8,163 ms | 
| ジャッジサーバーID (参考情報) | judge5 / judge4 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| other | AC * 33 | 
ソースコード
package no003;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		Graph g = new Graph(n);
		for(int i=0;i<n;i++) {
			int bc = Integer.bitCount(i+1);
			if (i - bc >= 0) {
				g.addEdge(i, i-bc, 1);
			}
			if (i + bc < n) {
				g.addEdge(i, i+bc, 1);
			}
		}
		int dist = g.minDistQueue(0)[n-1];
		System.out.println(dist == Graph.INF ? -1 : dist + 1);
	}
}
class Graph {
	public static final int INF = 1<<29;
	int n;
	ArrayList<Edge>[] graph;
	@SuppressWarnings("unchecked")
	public Graph(int n) {
		this.n = n;
		this.graph = new ArrayList[n];
		for(int i=0;i<n;i++) {
			graph[i] = new ArrayList<Edge>();
		}
	}
	public void addBidirectionalEdge(int from,int to,int cost) {
		addEdge(from,to,cost);
		addEdge(to,from,cost);
	}
	public void addEdge(int from,int to,int cost) {
		graph[from].add(new Edge(to, cost));
	}
	//O(E) all cost is 0 or 1
	public int[] minDistQueue(int s) {
		int[] d = new int[n];
		Arrays.fill(d, INF);
		ArrayDeque<Integer> q = new ArrayDeque<Integer>();
		q.add(s);
		d[s] = 0;
		while(!q.isEmpty()) {
			int v = q.pollFirst();
			for(Edge e:graph[v]) {
				int u = e.to;
				if (d[v] + e.cost < d[u]) {
					d[u] = d[v] + e.cost;
					if (e.cost == 0) {
						q.addFirst(u);
					}else{
						q.addLast(u);
					}
				}
			}
		}
		return d;
	}
	class Edge {
		int to;
		int cost;
		public Edge(int to,int cost) {
			this.to = to;
			this.cost = cost;
		}
	}
}
            
            
            
        