백준 [12851] "숨박꼭질 2"

Kimbab1004·2024년 4월 4일
0

Algorithm

목록 보기
25/102

오답

#include <iostream>
#include <deque>
#include <string>
#include <sstream>
#include <vector>
#include <string>
#include <queue>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <map>
#include <cstring>

using namespace std;
int n, k, t;
int min_ti = 999999999;
int ct = 0;
int ti = 0;
deque<pair<int, int>> q;
int visited[100001] = { 0 };

int walk_m(int a) {
	return a - 1;
}

int walk_p(int a) {
	return a + 1;
}
int tp(int a) {
	return 2 * a;
}

void hs(int a, int b) {
	
	q.push_back(make_pair(a, b));

	while (!q. empty()) {
		int x = q.front().first;
		int y = q.front().second;
		q.pop_front();

		if (x == k) {
			if (min_ti > y) {
				min_ti = y;
			}
			if (min_ti == y) {
				ct++;
			}
		}

		if (0 < x-1 && y+1 <= min_ti) {
			q.push_back(make_pair(x-1, y+1));
		}
		if (0 < x+1 && y+1 <= min_ti) {
			q.push_back(make_pair(x+1, y+1));
		}
		if (0 < 2*x && y+1 <= min_ti) {
			q.push_back(make_pair(2*x, y+1));
		}
	}
	cout << ct << "\n";
	cout << min_ti << "\n";
}

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

	cin >> n >> k;

	hs(n, 0);

	return 0;

}	

정답

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

#define MAX 100000

int N, K, ans, cnt;
bool check[100001];
queue<pair<int, int>> q; // <위치, 시간>

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

	cin >> N >> K;

	q.push({ N,0 });

	while (!q.empty())
	{
		int now = q.front().first;
		int time = q.front().second;
		q.pop();

		check[now] = true;

		// 이미 최소시간으로 방문한 경우
		if (cnt && ans == time && now == K)
			cnt++;

		// 처음으로 방문한 경우
		if (!cnt && now == K)
		{
			ans = time;
			cnt++;
		}

		if (now - 1 >= 0 && !check[now - 1])
			q.push({ now - 1,time + 1 });

		if (now + 1 <= MAX && !check[now + 1])
			q.push({ now + 1,time + 1 });

		if (2 * now <= MAX && !check[2 * now])
			q.push({ 2 * now,time + 1 });
	}
	cout << ans << '\n';
	cout << cnt << '\n';
}

0개의 댓글