A->B (16953)
https://www.acmicpc.net/problem/16953
๋ฌธ์
์ ์ A๋ฅผ B๋ก ๋ฐ๊พธ๋ ค๊ณ ํ๋ค. ๊ฐ๋ฅํ ์ฐ์ฐ์ ๋ค์๊ณผ ๊ฐ์ ๋ ๊ฐ์ง์ด๋ค.
2๋ฅผ ๊ณฑํ๋ค.
1์ ์์ ๊ฐ์ฅ ์ค๋ฅธ์ชฝ์ ์ถ๊ฐํ๋ค.
A๋ฅผ B๋ก ๋ฐ๊พธ๋๋ฐ ํ์ํ ์ฐ์ฐ์ ์ต์๊ฐ์ ๊ตฌํด๋ณด์.
์
๋ ฅ
์ฒซ์งธ ์ค์ A, B (1 โค A < B โค 109)๊ฐ ์ฃผ์ด์ง๋ค.
์ถ๋ ฅ
A๋ฅผ B๋ก ๋ฐ๊พธ๋๋ฐ ํ์ํ ์ฐ์ฐ์ ์ต์๊ฐ์ 1์ ๋ํ ๊ฐ์ ์ถ๋ ฅํ๋ค. ๋ง๋ค ์ ์๋ ๊ฒฝ์ฐ์๋ -1์ ์ถ๋ ฅํ๋ค.
์์ ์
๋ ฅ 1
2 162
์์ ์ถ๋ ฅ 1
5
์์ ์
๋ ฅ 2
4 42
์์ ์ถ๋ ฅ 2
-1
์์ ์
๋ ฅ 3
100 40021
์์ ์ถ๋ ฅ 3
5
๋ฌธ์ ์ ๊ตฌํ์ ์ด๋ ต์ง ์์์ง๋ง ์ญ์ ๋งํ๋ ๋ถ๋ถ์ ํ์ ์์ ๋งํ๋ค.
10์ 9์น์ ์ค๋ค๊ณ ํ๋๋ฐ, ์ ์ ๋์ ์๊ฐ ๋ค์ด์์ ๊ฒฐ๊ตญ ๋ก์ง์ ํ๊ฒ ๋๋ค๋ฉด ์ซ๊ฐ ์์ฒญ ๋ถ์ด๋ ๋ฟ๋ง์๋๋ผ ๊ธฐ๋ณธ์ ์ผ๋ก int ์ ํฌ๊ธฐ๊ฐ -20์ต๋ถํฐ 20์ต๊น์ง๋ผ๊ณ ์๊ณ ์๋ค โ 9์๋ฆฌ์๊ฐ 1์ต์ธ๋ฐ int์ ๋ฒ์๋ 10์๋ฆฌ์
๊ทธ๋ผ 20์ต์ด ๋ค์ด์์ ๊ฐ์ ๋๊ฒ๋๋ฉด int์ ๋ฒ์๋ฅผ ๋์ด๊ฐ๊ธฐ ๋๋ฌธ์ Long ํ์ ์ ์ฌ์ฉํด์ ํ์ด์ผ ํ๋ค!!
DFS
import java.util.*;
import java.io.*;
public class Main{
static long start, end;
static int result = -1;
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
start = Integer.parseInt(st.nextToken());
end = Integer.parseInt(st.nextToken());
fn(start, 0);
System.out.println(result);
}
public static void fn(long num, int count){
count++;
if(num == end){
result = count;
return;
}
if(num*2<=end){
fn(num*2, count);
}
if(num*10+1<=end){
fn(num*10+1, count);
}
}
}
BFS
import java.util.*;
import java.io.*;
public class Main{
static long result;
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
long start = Long.parseLong(st.nextToken());
long end = Long.parseLong(st.nextToken());
fn(start, end, 0);
System.out.println(result);
}
public static void fn(long start, long end, long count){
Queue<Long[]> q = new LinkedList<>();
q.add(new Long[]{start, count+1});
while(!q.isEmpty()){
Long[] tmp = q.poll();
long num = tmp[0];
long cnt = tmp[1];
if(num == end){
result = cnt;
return;
}
if(num*2<=end){
q.add(new Long[]{num*2, cnt+1});
}
if(num*10+1<=end){
q.add(new Long[]{num*10+1, cnt+1});
}
}
result = -1;
}
}
Last updated
Was this helpful?