๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/๋ฐฑ์ค€(BOJ)

[๋ฐฑ์ค€,c++] 13549๋ฒˆ - ์ˆจ๋ฐ”๊ผญ์งˆ3

by dkswnkk 2021. 11. 4.
 

13549๋ฒˆ: ์ˆจ๋ฐ”๊ผญ์งˆ 3

์ˆ˜๋นˆ์ด๋Š” ๋™์ƒ๊ณผ ์ˆจ๋ฐ”๊ผญ์งˆ์„ ํ•˜๊ณ  ์žˆ๋‹ค. ์ˆ˜๋นˆ์ด๋Š” ํ˜„์žฌ ์  N(0 ≤ N ≤ 100,000)์— ์žˆ๊ณ , ๋™์ƒ์€ ์  K(0 ≤ K ≤ 100,000)์— ์žˆ๋‹ค. ์ˆ˜๋นˆ์ด๋Š” ๊ฑท๊ฑฐ๋‚˜ ์ˆœ๊ฐ„์ด๋™์„ ํ•  ์ˆ˜ ์žˆ๋‹ค. ๋งŒ์•ฝ, ์ˆ˜๋นˆ์ด์˜ ์œ„์น˜๊ฐ€ X์ผ

www.acmicpc.net

#include <iostream>
#include <queue>
#define MAX 100001

using namespace std;


int N,K;    //N=์ˆ˜๋นˆ์ด๊ฐ€ ์žˆ๋Š” ์œ„์น˜, K=๋™์ƒ์ด ์žˆ๋Š” ์œ„์น˜
int visited[MAX];
int ans=MAX;

void bfs(int start,int time){
    priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>>pq;  //{์‹œ๊ฐ„,ํ˜„์žฌ ๊ฑฐ๋ฆฌ}
    pq.push({0,start});
    visited[start]=1;

    while(!pq.empty()){
        int time=pq.top().first;
        int start=pq.top().second;
        pq.pop();
        visited[start]=1;
        if(start==K){
            ans=time;
            return;
        }
        else{
            if(start>=0&&start-1<MAX&&!visited[start-1]) pq.push({time+1,start-1});    //๊ฑธ์„๋–„ ์‹œ๊ฐ„ +1
            if(start+1<MAX&&!visited[start+1]) pq.push({time+1,start+1});  //๊ฑธ์„๋•Œ ์‹œ๊ฐ„ +1
            if(start*2<MAX&&!visited[start*2]) pq.push({time,start*2});  //์ˆœ๊ฐ„์ด๋™ ํ• ๋•Œ ์‹œ๊ฐ„ +0
        }
    }

}

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(0);

    cin>>N>>K;
    bfs(N,0);
    cout<<ans;
}

๋Œ“๊ธ€