반응형
✏️ 문제 링크
https://www.acmicpc.net/problem/12851
12851번: 숨바꼭질 2
수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일 때
www.acmicpc.net
✏️ 문제 설명 (더보기 클릭 👆🏻)
✏️ 문제 코드 (BFS)
#include <bits/stdc++.h>
using namespace std;
using pii=pair<int, int>;
#define MAX 100001
vector<bool> v(MAX, false);
vector<int> ans;
int N, K;
void bfs(int s){
queue<pii> q;//position and depth
q.push({s, 0}); v[s]=true;
while(!q.empty()){
pii cur=q.front(); q.pop();
int pos=cur.first; int depth=cur.second;
// cout<<"pos: "<<pos<<" depth: "<<depth<<"\n";
v[pos]=true;
if(pos==K){// found sister
ans.push_back(depth);
continue;
}
if(pos-1>=0 and !v[pos-1]) q.push({pos-1, depth+1});
if(pos+1<MAX and !v[pos+1])q.push({pos+1, depth+1});
if(pos*2<MAX and !v[pos*2])q.push({pos*2, depth+1});
}
}
int main(){
cin>>N>>K;
bfs(N);
sort(ans.begin(), ans.end());
int mn=ans[0];
int cnt=0;
for(auto a: ans){
if(a!=mn)break;
cnt++;
}
cout<<mn<<"\n"<<cnt;
return 0;
}
⭐ if feedback and question : comment please⭐
반응형
'Algorithm 💫 > Problem Solving' 카테고리의 다른 글
[백준] 1504번: 특정한 최단 경로 / C++ (0) | 2021.09.24 |
---|---|
[백준] 1753번: 최단 경로 / C++ (0) | 2021.09.24 |
[백준] 14226번: 이모티콘 / C++ (0) | 2021.09.17 |
[백준] 13549번: 숨바꼭질3 / C++ (0) | 2021.09.17 |
[백준] 17086번: 아기상어 2 / C++ (0) | 2021.09.17 |
댓글