BOJ13549_์จ๋ฐ๊ผญ์ง3
Coding Test
2022. 9. 21. 15:58
๋ค์ต์คํธ๋ผ ์ฌ์ฉํ๋ค๊ณ ๋ฌด์กฐ๊ฑด ์ด์ค vector ๋ฃ์ ํ์ ์์.
์ด ๋ฌธ์ ์ ๊ฒฝ์ฐ graph์ ๊ฐ๊ฐ 3๊ฐ์ ๊ฐ์ ๋ฃ์๋๋ runtime error
graph ๋์ ์กฐ๊ฑด๋ฌธ์ผ๋ก ๋ฐ๊ฟจ๋๋ ๋ฉ๋ชจ๋ฆฌ ์ด๊ณผ ์๋จ
์ดํ ๋ ํ๋ ธ๋๋ฐ if(b > k * 2) ๋ผ๋ ์ด์ํ ์กฐ๊ฑด๋ฌธ ๋ฃ์ด์ ํ๋ฆผ
// graph ์ ๊ฐ๊ฐ 3๊ฐ์ ๊ฐ์ ๋ฃ์ผ๋ฉด runtime error
// graph ๋์ ์กฐ๊ฑด๋ฌธ์ผ๋ก bad alloc ์์ฐ
// if(b > k * 2) ๋ผ๋ ์ด์ํ ์กฐ๊ฑด๋ฌธ ๋ฃ์ด์ ํ๋ฆผ
#include <iostream>
#include <queue>
#include <vector>
#define INF int(1e5)
using namespace std;
struct Edge {
int to;
int cost;
};
struct cmp {
bool operator() (Edge a, Edge b) {
if (a.cost <= b.cost) return false;
else return true;
}
};
int n, k;
int d[100001];
// ๊ฐ ๋
ธ๋๋ง๋ค ๊ฐ์ ์ด 3๊ฐ์ง ์๋ค๊ณ ๊ฐ์
// +1, -1 : ๊ฐ์ค์น +1
// *2 : ๊ฐ์ค์น 0
void dijkstra() {
priority_queue<Edge, vector<Edge>, cmp> pq;
pq.push({n, 0}); // ์๋น์ ์์น
d[n] = 0;
int X[2] = {-1, 1};
while(!pq.empty()) {
Edge cur = pq.top(); //ํ์ฌ ์์น, ํ์ฌ ์๊ฐ
pq.pop();
if (d[cur.to] < cur.cost) continue;
int b, b_cost;
for(int i = 0; i < 3; i++) {
if (i == 2) {
b = cur.to * 2;
b_cost = cur.cost;
} else {
b = cur.to + X[i];
b_cost = cur.cost + 1;
}
if (b < 0 || b > 100000) continue;
if (d[b] <= b_cost) continue;
d[b] = b_cost;
pq.push({b, b_cost});
}
}
}
int main(void) {
ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
cin >> n >> k;
// ๋น์ฉ ๋ฐฐ์ด ์ด๊ธฐํ
for (int i = 0; i <= 100000; i++) {
d[i] = INF;
}
dijkstra();
cout << d[k] << endl;
}
'Coding Test' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
BOJ1504_ํน์ ํ ์ต๋จ ๊ฒฝ๋ก (0) | 2022.09.22 |
---|---|
BOJ1238_ํํฐ (C++) (0) | 2022.09.21 |
BOJ 1717: ์งํฉ์ ํํ (0) | 2022.07.22 |
Union-Find (ํฉ์งํฉ ์ฐพ๊ธฐ) (0) | 2022.07.22 |
2022 ์๋ฐ๊ธฐ ์ผ์ฑSDS ์ฝ๋ฉํ ์คํธ ํ๊ธฐ (0) | 2022.07.22 |