์๊ณ ๋ฆฌ์ฆ
๋ฐฑ์ค_5014_์คํํธ๋งํฌ
shj718
2022. 7. 6. 21:13
๐โ๏ธ ๋ฌธ์
https://www.acmicpc.net/problem/5014
5014๋ฒ: ์คํํธ๋งํฌ
์ฒซ์งธ ์ค์ F, S, G, U, D๊ฐ ์ฃผ์ด์ง๋ค. (1 ≤ S, G ≤ F ≤ 1000000, 0 ≤ U, D ≤ 1000000) ๊ฑด๋ฌผ์ 1์ธต๋ถํฐ ์์ํ๊ณ , ๊ฐ์ฅ ๋์ ์ธต์ F์ธต์ด๋ค.
www.acmicpc.net
๐งฉ ์๊ณ ๋ฆฌ์ฆ
์์์ ์ผ๋ก๋ถํฐ ๋ชจ๋ ์ ์ ์ ๋ฐฉ๋ฌธํ๋ฉฐ ๊ฐ์ ์ ๊ฐ์ค์น๊ฐ 1์ด๊ณ ๋๋ฌ์ผ ํ๋ ๋ฒํผ์ ์์ ์ต์๊ฐ์ ๊ตฌํ๋ ๋ฌธ์ ์ด๋ฏ๋ก BFS ์๊ณ ๋ฆฌ์ฆ ์ฌ์ฉ
๐ก ์์ด๋์ด
๊ธฐ๋ณธ์ ์ธ BFS ๋ฌธ์ ์๋ค.
๐ฉ๐ป ์ฝ๋
#include <iostream>
#include <queue>
using namespace std;
bool visited[1000001];
int dist[1000001];
int main() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
// input
int floor, start, goal, up, down;
cin >> floor >> start >> goal >> up >> down;
// BFS
queue<int> q;
q.push(start);
visited[start] = true;
dist[start] = 0;
while (!q.empty()) {
int cur = q.front();
q.pop();
int next1 = cur + up;
int next2 = cur - down;
if (next1 >= 1 && next1 <= floor && visited[next1] == false) {
q.push(next1);
visited[next1] = true;
dist[next1] = dist[cur] + 1;
}
if (next2 >= 1 && next2 <= floor && visited[next2] == false) {
q.push(next2);
visited[next2] = true;
dist[next2] = dist[cur] + 1;
}
}
// output
if (visited[goal]) {
cout << dist[goal] << '\n';
}
else {
cout << "use the stairs" << '\n';
}
return 0;
}