結果
| 問題 | No.3 ビットすごろく |
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2018-03-04 15:00:22 |
| 言語 | Java (openjdk 23) |
| 結果 |
AC
|
| 実行時間 | 98 ms / 5,000 ms |
| コード長 | 2,836 bytes |
| コンパイル時間 | 4,074 ms |
| コンパイル使用メモリ | 81,392 KB |
| 実行使用メモリ | 40,212 KB |
| 最終ジャッジ日時 | 2024-07-01 08:56:32 |
| 合計ジャッジ時間 | 7,576 ms |
|
ジャッジサーバーID (参考情報) |
judge5 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 33 |
ソースコード
package yukicoder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class P3 {
static long[] dist;
static long INF = 100000000000000000L;
static ArrayList<ArrayList<Edge>> adj;
static class Edge {
int to;
long w;
Edge(int _to, long _w) {
this.to = _to;
this.w = _w;
}
@Override
public String toString() {
return "(to=" + to + ", w=" + w + ")";
}
}
static class NextNode {
int id;
long cost;
NextNode(int _id, long _cost) {
id = _id; cost = _cost;
}
}
static void initG(int V) { // V: the number of vertexes
for(int i=0; i<V; i++) {
adj.add(new ArrayList<Edge>());
}
}
static void dijkstra(int s) {
Arrays.fill(dist, INF);
dist[s] = 0;
PriorityQueue<NextNode> pq = new PriorityQueue<NextNode>(new Comparator<NextNode>() {
public int compare(NextNode n1, NextNode n2) {
if(n1.cost > n2.cost) return 1;
else if(n1.cost==n2.cost) return 0;
else return -1;
}
});
pq.add(new NextNode(s, 0));
while(!pq.isEmpty()) {
NextNode cn = pq.poll();
if(cn.cost > dist[cn.id]) continue;
for(Edge e : adj.get(cn.id)) {
if(cn.cost + e.w < dist[e.to]) {
dist[e.to] = cn.cost + e.w;
pq.add(new NextNode(e.to, dist[e.to]));
}
}
}
}
public static void main(String[] args) throws IOException {
MyScanner sc = new MyScanner(System.in);
int n = sc.nextInt();
dist = new long[n+1];
adj = new ArrayList<ArrayList<Edge>>(n+1);
initG(n+1);
for(int i=1; i<=n; i++) {
int d = digit(i);
if(0<=i+d && i+d<=n) adj.get(i).add(new Edge(i+d, 1));
if(0<=i-d && i-d<=n) adj.get(i).add(new Edge(i-d, 1));
}
dijkstra(1);
if(dist[n]>=INF) {
System.out.println(-1);
} else {
System.out.println(dist[n]+1);
}
}
public static int digit(int n) {
int ret = 0;
while(n>0) {
if(n%2==1) ret++;
n/=2;
}
return ret;
}
static class MyScanner
{
BufferedReader br;
StringTokenizer st;
public MyScanner(InputStream s)
{
br=new BufferedReader(new InputStreamReader(s));
}
public String nextLine() throws IOException
{
return br.readLine();
}
public String next() throws IOException
{
while(st==null || !st.hasMoreTokens())
st=new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException
{
return Integer.parseInt(next());
}
public double nextDouble() throws IOException
{
return Double.parseDouble(next());
}
public boolean ready() throws IOException
{
return br.ready();
}
public long nextLong() throws IOException
{
return Long.parseLong(next());
}
}
}