[BOJ] 13549๋ฒ | ์จ๋ฐ๊ผญ์ง 3 (C++)
2023. 12. 6. 23:00ใCoding Test/BOJ
๐๋ฌธ์ ๋ณด๋ฌ๊ฐ๊ธฐ
13549๋ฒ: ์จ๋ฐ๊ผญ์ง 3
์๋น์ด๋ ๋์๊ณผ ์จ๋ฐ๊ผญ์ง์ ํ๊ณ ์๋ค. ์๋น์ด๋ ํ์ฌ ์ N(0 โค N โค 100,000)์ ์๊ณ , ๋์์ ์ K(0 โค K โค 100,000)์ ์๋ค. ์๋น์ด๋ ๊ฑท๊ฑฐ๋ ์๊ฐ์ด๋์ ํ ์ ์๋ค. ๋ง์ฝ, ์๋น์ด์ ์์น๊ฐ X์ผ ๋
www.acmicpc.net
๐งโ๐ป ํ์ด ๊ณผ์
์ต๋จ ๊ฒฝ๋ก ์๊ณ ๋ฆฌ์ฆ์ ์ฐ์ต ์ค์ ์์ด, ์ ๋ ๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ์ผ๋ก ํ์์ต๋๋ค. (๋น์ฉ์ ์์๊ฐ ์๊ธฐ ๋๋ฌธ)
์์ ์์น๋ N, ๋์ฐฉ ์์น๋ K๋ก ์ฃผ์ด์ง๋๋ค.
- N์์ i๋ฒ์งธ ๋
ธ๋๋ก ๊ฐ๋ ๋ฐ์ ๋๋ ์ต์ ์๊ฐ์ ์ ์ฅํ๋ ๋ฐฐ์ด, times๋ฅผ ์ ์ธํฉ๋๋ค.
๋ฒ์๊ฐ 0 ~ 100,000์ด๋, ์ด ๋ฒ์๋ฅผ ํฌํจํ ์ ์๋ ๋งํผ์ ํฌ๊ธฐ๋ก ์ ์ธ ํ, ๋ฌดํ๋ ๊ฐ์ผ๋ก ์ด๊ธฐํํฉ๋๋ค. - times[N] = 0 ์ผ๋ก ์ด๊ธฐํ ํ, <์๊ฐ, ๋ ธ๋> ์ ๋ณด๋ฅผ ๋ด๋ ์ฐ์ ์์ ํ์ ์์์ ์ ๋ณด <0, N>์ ๋ฃ์ต๋๋ค.
- ์ด๋ ๊ท์น์ ๋ฐ๋ผ -1, +1, *2๋ฅผ ์ ์ฉํ ๋ค์ ์์น(next)๋ฅผ ๊ณ์ฐํ๊ณ , ํ์ฌ ์๊ฐ์์ ๋ค์ ์์น๋ก ์ด๋ํ๋ ๋ฐ ํ์ํ ์๊ฐ(0 ๋๋ 1)์ ๋ํ nextTime์ ๊ณ์ฐํฉ๋๋ค.
- nextTime์ด ๊ธฐ์กด์ next ๋ ธ๋๋ก ์ด๋ํ๋ ์๊ฐ๋ณด๋ค ๋ง๋ค๋ฉด, ๋์ด๊ฐ๋๋ค.
- ๊ธฐ์กด์ next ๋ ธ๋๋ก ์ด๋ํ๋ ๋ฐ ๊ฑธ๋ฆฌ๋ ์๊ฐ vs ํ์ฌ ๋ ธ๋๋ฅผ ๊ฒฝ์ ํด์ next ๋ ธ๋๋ก ๊ฐ๋ ์๊ฐ ์ค์ ์์ ๊ฒ์ times[next]์ ๋ฃ๊ณ , ํ์ ์ด ์ ๋ณด๋ฅผ ๋ฃ์ต๋๋ค.
- ๋ง์ฝ next == K๋ผ๋ฉด, times[K] = min(times[K], nextTime) ์ผ๋ก ๊ฐฑ์ ํด์ค๋๋ค.
- ํ๊ฐ ๋น ๋๊น์ง, 3 ~ 5 ๊ณผ์ ์ ๋ฐ๋ณตํฉ๋๋ค.
โ๏ธ ์์ค ์ฝ๋ ๋ฐ ๊ฒฐ๊ณผ
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
#define FAST_IO ios::sync_with_stdio(false); cout.tie(NULL); cin.tie(NULL);
#define MAX 100000
#define INF 1000000000
int Calculate(int node, int i) {
switch(i) {
case 0: return node - 1;
case 1: return node + 1;
case 2: return node * 2;
}
return 0;
}
int FindMinTime(vector<int>& times, int start, int K) {
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
// <์ต์ ์๊ฐ, ๋
ธ๋>
times[start] = 0;
pq.emplace(0, start);
while (!pq.empty()) {
pair<int, int> current = pq.top();
int time = current.first;
int node = current.second;
pq.pop();
for (int i = 0; i < 3; i++) {
int next = Calculate(node, i);
if (next < 0 or next > MAX or times[next] < time)
continue;
bool isTeleport = (i == 2);
int nextTime = time + !isTeleport;
if (next == K)
times[K] = min(nextTime, times[K]);
if (nextTime < times[next]) {
times[next] = nextTime;
pq.emplace(nextTime, next);
}
}
}
return times[K];
}
int main() {
FAST_IO
int N, K;
cin >> N >> K;
vector<int> times(MAX + 1, INF);
int answer = FindMinTime(times, N, K);
cout << answer;
return 0;
}

728x90
๋ฐ์ํ
'Coding Test > BOJ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[BOJ] 14502๋ฒ | ์ฐ๊ตฌ์ (C++) (0) | 2023.12.13 |
---|---|
[BOJ] 17472๋ฒ | ๋ค๋ฆฌ ๋ง๋ค๊ธฐ 2 (C++) (0) | 2023.12.12 |
[BOJ] 16928๋ฒ | ๋ฑ๊ณผ ์ฌ๋ค๋ฆฌ ๊ฒ์ (C++) (0) | 2023.12.01 |
[BOJ] 9935๋ฒ | ๋ฌธ์์ด ํญ๋ฐ (C++) (1) | 2023.10.08 |
[BOJ] 2110๋ฒ | ๊ณต์ ๊ธฐ ์ค์น (C++) (0) | 2023.10.08 |