알고리즘

백준 5014번 스타트링크 C++

영춘권의달인 2022. 1. 14. 11:58

출처 : https://www.acmicpc.net/problem/5014

 

어렵지 않은 bfs 탐색 문제이다.

 

#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>

using namespace std;
typedef long long ll;

int f, s, g, u, d;
vector<bool> found(1000001, false);

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	cin >> f >> s >> g >> u >> d;

	queue<pair<int, int>> q;
	q.push({ s,0 });
	found[s] = true;
	int ans = -1;
	bool isPossible = false;
	while (!q.empty()) {
		auto curr = q.front();
		q.pop();
		if (curr.first == g) {
			isPossible = true;
			ans = curr.second;
			break;
		}
		if (u != 0) {
			int nextFloor = curr.first + u;
			if (nextFloor <= f) {
				if (!found[nextFloor]) {
					q.push({ nextFloor,curr.second + 1 });
					found[nextFloor] = true;
				}
			}
		}
		if (d != 0) {
			int nextFloor = curr.first - d;
			if (nextFloor > 0) {
				if (!found[nextFloor]) {
					q.push({ nextFloor,curr.second + 1 });
					found[nextFloor] = true;
				}
			}
		}
	}
	if (isPossible) {
		cout << ans;
	}
	else {
		cout << "use the stairs";
	}
};