π [λ°±μ€μκ³ λ¦¬μ¦ νμ΄] Q.1697 μ¨λ°κΌμ§ λ¬Έμ νμ΄
π λ¬Έμ
https://www.acmicpc.net/problem/1697
μλΉμ΄λ λμκ³Ό μ¨λ°κΌμ§μ νκ³ μλ€. μλΉμ΄λ νμ¬ μ N(0 β€ N β€ 100,000)μ μκ³ , λμμ μ K(0 β€ K β€ 100,000)μ μλ€.
μλΉμ΄λ κ±·κ±°λ μκ°μ΄λμ ν μ μλ€. λ§μ½, μλΉμ΄μ μμΉκ° XμΌ λ κ±·λλ€λ©΄ 1μ΄ νμ X-1 λλ X+1λ‘ μ΄λνκ² λλ€.
μκ°μ΄λμ νλ κ²½μ°μλ 1μ΄ νμ 2*Xμ μμΉλ‘ μ΄λνκ² λλ€.
μλΉμ΄μ λμμ μμΉκ° μ£Όμ΄μ‘μ λ, μλΉμ΄κ° λμμ μ°Ύμ μ μλ κ°μ₯ λΉ λ₯Έ μκ°μ΄ λͺ μ΄ νμΈμ§ ꡬνλ νλ‘κ·Έλ¨μ μμ±νμμ€.
π μ κ·Όλ²
μλΉμ΄μ λμμ΄ λͺ μ΄ νμ κ°μ μμΉμ μμ μ μλμ§ κ΅¬νλ λ¬Έμ μ
λλ€.
ꡬν΄μΌ νλ λ΅μ΄ λͺ μ΄ μΈμ§μ΄κ³
1μ΄ λ¨μλ‘ κ±·κ±°λ μκ°μ΄λμ΄ κ°λ₯ν©λλ€.
μ¦ κ°μ€μΉκ° 1μ΄λ―λ‘ BFSλ‘ κ°μ₯ λΉ λ₯Έ μκ°μ ꡬν μ μμ΅λλ€.
1μ΄ νμ μ΄λν μ μλ μμΉλ€μ λͺ¨λ BFS νμμ ν©λλ€.
BFS νμμ νλ€ λμμ μμΉλ‘ μ΄λνμ λ μκ°(μ΄)μ΄
μ λ΅μ
λλ€.
π» μ½λ
package problem.bfsdfs;
import java.io.*;
import java.util.LinkedList;
import java.util.Queue;
public class Main_1697 {
static int n, k;
static boolean[] visited;
static int[] position;
static Queue<Integer> queue = new LinkedList();
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
input();
int answer = bfs(n);
bw.write(Integer.toString(answer));
bw.flush();
bw.close();
}
public static void input() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] input = br.readLine().split(" ");
n = Integer.parseInt(input[0]);
k = Integer.parseInt(input[1]);
visited = new boolean[200001];
position = new int[200001];
br.close();
}
public static int bfs(int n) {
queue.offer(n);
visited[n] = true;
while (!queue.isEmpty()) {
int move = queue.poll();
if(move * 2 > 200001)
continue;
if (move * 2 <= 200001 && !visited[move * 2]) {
position[move * 2] = position[move] + 1;
visited[move * 2] = true;
queue.offer((move * 2));
}
if (move >= 1 && !visited[move - 1]) {
position[move - 1] = position[move] + 1;
visited[move - 1] = true;
queue.offer((move - 1));
}
if (move <= 200000 && !visited[move + 1]) {
position[move + 1] = position[move] + 1;
visited[move + 1] = true;
queue.offer((move + 1));
}
if (visited[k] == true) {
return position[k];
}
}
return -1;
}
}
Written on July 3, 2020