컴슈니 - 문제해결

[백준] 2412번: 암벽 등반

컴슈니 2023. 7. 30. 18:53

문제

https://www.acmicpc.net/problem/2412

 

2412번: 암벽 등반

어떤 암벽에 n(1 ≤ n ≤ 50,000)개의 홈이 파져 있다. 각각의 홈의 좌표는 (x, y)와 같이 표현되는데, |a - x| ≤ 2이고 |b - y| ≤ 2이면 (x, y)에서 (a, b)로 이동할 수 있다. 이와 같이 홈들을 이용하여 이동

www.acmicpc.net

문제 해결

BFS + 이분 탐색(lower_bound)

 

결과

코드

#include<iostream>
#include<algorithm>
#include<queue>
#include<map>
#include<cmath>
using namespace std;

using pii = pair<int, int>;
vector<pii> arr;
map<pii, bool> visit;
int ans = -1;

bool comp(const pii& a, const pii& b)
{
	return a.second < b.second;
}

int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);

	int n = 0, m = 0;
	cin >> n >> m;

	for (int i = 0; i < n; i++)
	{
		int a, b;
		cin >> a >> b;
		arr.push_back({ a,b });
	}

	sort(arr.begin(), arr.end(),comp);

	queue<pair<pii, int>> q;
	q.push({ {0,0},0 });

	while (!q.empty())
	{
		int a = q.front().first.first;
		int b = q.front().first.second;
		int cnt = q.front().second;
		q.pop();

		if (b == m)
		{
			ans = cnt;
			break;
		}

		if (visit[{a, b}]) continue;
		visit[{a, b}] = true;

		auto it = lower_bound(arr.begin(), arr.end(), pii(0, b - 2), comp) - arr.begin();

		for (int i = it; i < n && abs(arr[i].second - b) <= 2; i++)
		{
			int x = arr[i].first;
			int y = arr[i].second;

			if (!visit[{x, y}] && abs(x - a) <= 2)
				q.push({ {x,y},cnt+1 });
		}
	}
	cout << ans;
	return 0;
}
728x90
반응형