Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 구현
- Unreal Engine 5
- 그래프
- 다이나믹 프로그래밍
- 자료구조
- 다익스트라
- 누적 합
- 유니티
- c++
- 수학
- 트리
- VR
- 알고리즘
- 정렬
- 스택
- 백트래킹
- ue5
- 문자열
- 시뮬레이션
- BFS
- 브루트포스
- DFS
- 그리디 알고리즘
- 우선순위 큐
- XR Interaction Toolkit
- Team Fortress 2
- 백준
- 투 포인터
- 유니온 파인드
- 재귀
Archives
- Today
- Total
1일1알
백준 16953번 A->B (C++) 본문
bfs로 문제를 해결하였다.
초기 cnt=1
처음 큐에 pair로 (A, cnt)을 넣고 (A * 2, cnt + 1) 와 (A * 10 + 1, cnt + 1)을 bfs로 탐색하면서 A의 값이 B의 값과 같아지면 cnt를 출력하는 방식으로 해결하였다.
같은 숫자를 또 방문하는 것을 방지하기 위해 탐색 시간 복잡도가 O(1)인 unordered_set에 방문한 값을 넣어줘서 중복을 방지하고, A * 2나 A * 10 + 1이 B보다 커지면 큐에 넣지 않는 식으로 구현하였다.
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <unordered_set>
using namespace std;
typedef long long ll;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
ll a, b;
cin >> a >> b;
queue<pair<ll, ll>> q;
unordered_set<ll> us;
q.push({ a,1 });
us.insert(a);
ll ans = -1;
while (!q.empty()) {
auto a = q.front();
if (a.first == b) {
ans = a.second;
break;
}
q.pop();
if (us.find(a.first * 2) == us.end() && a.first * 2 <= b) {
q.push({ a.first * 2,a.second + 1 });
us.insert(a.first * 2);
}
if (us.find(a.first * 10 + 1) == us.end() && a.first * 10 + 1 <= b) {
q.push({ a.first * 10 + 1,a.second + 1 });
us.insert(a.first * 10 + 1);
}
}
cout << ans;
};
'알고리즘' 카테고리의 다른 글
백준 1051번 숫자 정사각형 C++ (0) | 2021.10.21 |
---|---|
백준 12851번 숨바꼭질2 C++ (0) | 2021.10.20 |
백준 11660번 구간 합 구하기 5 C++ (0) | 2021.10.18 |
백준 11725번 트리의 부모 찾기 C++ (0) | 2021.10.17 |
백준 9465번 스티커 C++ (0) | 2021.10.16 |