[백준 1963번] 소수 경로

2017. 7. 24. 00:08알고리즘/백준

반응형









소스코드


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>
using namespace std;
 
int a, b, visit[10001= { 0, };
int que[10001], head = 0, tail = 0;
int n_que[10001], n_head = 0, n_tail = 0;
 
void push(int a) {
    que[tail++= a;
}
int pop() {
    return que[head++];
}
void n_push(int a) {
    n_que[n_tail++= a;
}
int n_pop() {
    return n_que[n_head++];
}
 
int chk(int a) {
    for (int i = 2; i < a; i++) {
        if (a%i == 0return 0;
    }
    return 1;
}
 
void bfs() {
    while (1) {
        int num = pop();
        int cnt = n_pop();
        if (num == b) {
            cout << cnt << '\n';
            break;
        }
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 10; j++) {
                if (i == 0 && j == 0) {
                    continue;
                }
                char tmp[4= { (num / 1000+ '0', ((num % 1000/ 100+ '0', (((num % 1000) % 100/ 10+ '0', (((num % 1000) % 100) % 10+ '0' };
                if ((tmp[i] - '0'!= j) {
                    tmp[i] = j + '0';
                    int tmp_num = (tmp[0- '0'* 1000 + (tmp[1- '0'* 100 + (tmp[2- '0'* 10 + (tmp[3- '0');
                    if (chk(tmp_num) == 1 && visit[tmp_num]==0) {
                        visit[tmp_num] = 1;
                        push(tmp_num);
                        n_push(cnt + 1);
                    }
                }
            }
        }
        if (head == tail) {
            cout << "Impossible" << '\n';
            break;
        }
    }
}
 
int main() {
    int tc;
    cin >> tc;
    while (tc>0) {
        cin >> a >> b;
        head = 0, tail = 0, n_head=0, n_tail=0;
        for (int i = 0; i < 10000; i++) {
            visit[i] = 0;
        }
        push(a);
        n_push(0);
        bfs();
        tc--;
    }
    return 0;
}
cs


반응형

'알고리즘 > 백준' 카테고리의 다른 글

[백준 2879번] 코딩은 예쁘게  (0) 2017.07.25
[백준 9465번] 스티커  (0) 2017.07.24
[백준 10819번] 차이를 최대로  (0) 2017.07.23
[백준 1107번] 리모컨  (2) 2017.07.23
[백준 5397번] 키로거  (0) 2017.07.23