HyeLog

λ°±μ€€_1963_μ†Œμˆ˜ 경둜 λ³Έλ¬Έ

μ•Œκ³ λ¦¬μ¦˜

λ°±μ€€_1963_μ†Œμˆ˜ 경둜

shj718 2022. 7. 2. 21:43

πŸ™‹‍♀️ 문제

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

 

1963번: μ†Œμˆ˜ 경둜

μ†Œμˆ˜λ₯Ό μœ λ‚œνžˆλ„ μ’‹μ•„ν•˜λŠ” μ°½μ˜μ΄λŠ” κ²Œμž„ 아이디 λΉ„λ°€λ²ˆν˜Έλ₯Ό 4자리 ‘μ†Œμˆ˜’둜 μ •ν•΄λ†“μ•˜λ‹€. μ–΄λŠ λ‚  μ°½μ˜μ΄λŠ” μΉœν•œ μΉœκ΅¬μ™€ λŒ€ν™”λ₯Ό λ‚˜λˆ„μ—ˆλŠ”λ°: “이제 슬슬 λΉ„λ²ˆ λ°”κΏ€ λ•Œλ„ λμž–μ•„” “응 μ§€κΈˆ

www.acmicpc.net

 

🧩 μ•Œκ³ λ¦¬μ¦˜

βœ”οΈλͺ¨λ“  정점 λ°©λ¬Έ, μ΅œμ†Œ 횟수 κ΅¬ν•˜κΈ° → BFS μ•Œκ³ λ¦¬μ¦˜

정점: 수

κ°„μ„ : 수 → 수 (κ°€μ€‘μΉ˜ = 1)

 

βœ”οΈμ†Œμˆ˜ κ΅¬ν•˜κΈ°→ μ—λΌν† μŠ€ν…Œλ„€μŠ€μ˜ 체

 

πŸ’‘ 아이디어

-ν…ŒμŠ€νŠΈμΌ€μ΄μŠ€λ§ˆλ‹€ BFS 진행.

-μ†Œμˆ˜ νŒλ³„ λ°°μ—΄, λ°©λ¬Έ μ—¬λΆ€ λ°°μ—΄, 횟수 μ €μž₯ 배열을 ν™œμš©.

-수의 ν•œ 자릿수만 λ°”κΎΈκΈ° → 수λ₯Ό string으둜 λ°”κΏ”μ„œ 진행. (to_string(), stoi())

 

πŸ‘©‍πŸ’» μ½”λ“œ

#include <iostream>
#include <queue>
#include <cstring>

using namespace std;

int prime[10000];
bool visited[10000];
int dist[10000];

int change(int num, int pos, int digit) { // ν•œ 자리 숫자 λ°”κΎΈλŠ” ν•¨μˆ˜
	if (pos == 0 && digit == 0) return -1; // λ„€ 자리 μˆ˜κ°€ μ•„λ‹Œ 경우 -1 리턴
	string s = to_string(num);
	s[pos] = digit + '0';
	return stoi(s);
}

void bfs(int n) { // BFS ν•¨μˆ˜
	queue<int> q;
	q.push(n);
	visited[n] = true;
	dist[n] = 0;
	
	while (!q.empty()) {
		int cur = q.front();
		q.pop();

		for (int i = 0; i < 4; i++) {
			for (int j = 0; j <= 9; j++) {
				int next = change(cur, i, j);
				if (next != -1) { // λ„€ 자리 μˆ˜κ°€ 맞으면
					if (prime[next] != 0 && visited[next] == false) {
						q.push(next);
						visited[next] = true;
						dist[next] = dist[cur] + 1;
					}
				}
			}
		}
	}
}

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

	// μ†Œμˆ˜ κ΅¬ν•˜κΈ° (μ—λΌν† μŠ€ν…Œλ„€μŠ€μ˜ 체)
	for (int i = 2; i <= 9999; i++) {
		prime[i] = i;
	}
	for (int i = 2; i <= 9999; i++) {
		if (prime[i] == 0) continue;
		for (int j = i + i; j <= 9999; j += i) {
			prime[j] = 0;
		}
	}

	// input
	int t, n, m;
	cin >> t;

	// ν…ŒμŠ€νŠΈμΌ€μ΄μŠ€λ§ˆλ‹€ BFS
	for (int i = 0; i < t; i++) {
		cin >> n >> m;
		// μ΄ˆκΈ°ν™”
		memset(visited, false, sizeof(visited));
		memset(dist, 0, sizeof(dist));
		// BFS
		bfs(n);
		// output
		if (visited[m] == true) {
			cout << dist[m] << '\n';
		}
		else {
			cout << "Impossible" << '\n';
		}
	}
	return 0;
}