Notice
Recent Posts
Recent Comments
Link
«   2026/06   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
Archives
Today
Total
관리 메뉴

dh-winternagi 님의 블로그

(13913) 숨바꼭질 4 본문

백준 (C++)/Solve

(13913) 숨바꼭질 4

dh-winternagi 2026. 4. 20. 08:11

https://www.acmicpc.net/problem/13913

단계별로 풀어보기

32단계(동적 계획법과 최단거리 역추적) 6번째

 

 

 

#include <iostream>
#include <queue>
using namespace std;

int main() {
  int n, k;
  
  cin >> n >> k;
  
  vector<int> dist(100001, -1), from(100001, -1), res;
  
  queue<int> q;
  
  q.push(n);
  dist[n]= 0;
  
  while(!q.empty()){
    int now= q.front();
    q.pop();
    
    if(now==k)  break;
    
    if(now-1>=0 && dist[now-1]==-1){
      dist[now-1]= dist[now]+1;
      from[now-1]= now;
      q.push(now-1);
    }
    
    if(now+1<=100000 && dist[now+1]==-1){
      dist[now+1]= dist[now]+1;
      from[now+1]= now;
      q.push(now+1);
    }
    
    if(2*now<=100000 && dist[2*now]==-1){
      dist[2*now]= dist[now]+1;
      from[2*now]= now;
      q.push(2*now);
    }
  }
  
  cout << dist[k] << "\n";
  
  while(k>=0){
    res.push_back(k);
    k= from[k];
  }
  
  for(int i=res.size()-1;i>=0;i--)  cout << res[i] << " ";
  
  return 0;
}

'백준 (C++) > Solve' 카테고리의 다른 글

(11779) 최소비용 구하기  (0) 2026.04.20
(9019) DSLR  (0) 2026.04.20
(2618) 경찰차  (0) 2026.04.20
(9252) LCS 2  (0) 2026.04.20
(14003) 가장 긴 증가하는 부분 수열 5  (0) 2026.04.20