[백준] 16953번 A -> B (JAVA, DFS)

728x90
반응형

www.acmicpc.net/problem/16953

 

16953번: A → B

첫째 줄에 A, B (1 ≤ A < B ≤ 109)가 주어진다.

www.acmicpc.net

뒤에 1을 붙여주는 연산은 숫자 x*10+1 이라서 정수 범위 대략 2*10^9을 넘어가서 런타임에러가 난다.

long형으로 바꿔줘야 된다.

import java.util.Scanner;

public class Main{
	static long a,b;
	static long answer;
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
			answer=-1;
			a=sc.nextInt();
			b=sc.nextInt();
			go(a,b,0);
			if(answer==-1) {
				System.out.println(-1);
			}else {
				System.out.println(answer+1);
			}
		
	}
	private static void go(long x,long y,long cnt) {
		if(x==y) {
			if(answer==-1 || answer>cnt) {
				answer=cnt;
			}
			return;
		}
		if(2*x<=y) {
			go(2*x,y,cnt+1);
		}
		if(10*x+1<=y) {
			go(10*x+1,y,cnt+1);
		}
		
		
	}
}
728x90
반응형
TAGS.

Comments