티스토리 뷰

알고리즘/백준

[C++/BFS] 백준 9019 DSLR

waterground 2019. 3. 31. 14:28

코드

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
76
77
78
#include <iostream>
#include <queue>
#include <string>
using namespace std;
 
struct n {
    int number; // 숫자
    string res; // 연산과정
};
 
bool isVisit[10001];
queue<struct n> q;
 
int calD(int n){ // D연산
    return (n * 2) % 10000;
}
 
int calS(int n) { // S연산
    return n-1 >= 0 ? n-1 : 9999;
}
 
int calL(int n) { // L연산
    return (n % 1000* 10 + n / 1000;
}
 
int calR(int n) { // R연산
    return n / 10 + (n % 10* 1000;
}
 
void solve(int start, int end) {
    int D,S,L,R;
    q.push({ start, ""}); // 숫자, 연산과정
    isVisit[start] = true// 방문 표시
 
    while (!q.empty()) {
        int nowNum = q.front().number; // 숫자
        string nowStr = q.front().res; // 연산 과정
        q.pop();
 
        if (nowNum == end) {
            // 연산 결과가 원하던 값일 경우 연산 과정 출력 후 종료
            cout << nowStr << endl;
            return;
        }
 
        D = calD(nowNum);
        S = calS(nowNum);
        L = calL(nowNum);
        R = calR(nowNum);
        if (!isVisit[D]) {
            isVisit[D] = true// 방문 표시
            q.push({ D, nowStr+"D"}); // 연산후 값, 바뀐 연산과정 큐에 넣기
        }
        if (!isVisit[S]) {
            isVisit[S] = true// 방문표시
            q.push({ S, nowStr+"S"}); // 연산후 값, 바뀐 연산과정 큐에 넣기
        }
        if (!isVisit[L]) {
            isVisit[L] = true// 방문표시
            q.push({ L, nowStr+"L"}); // 연산후 값, 바뀐 연산과정 큐에 넣기
        }
        if (!isVisit[R]) {
            isVisit[R] = true// 방문표시
            q.push({ R, nowStr+"R"}); // 연산후 값, 바뀐 연산과정 큐에 넣기
        }
    }
}
 
int main() {
    int t,n, res;
    cin >> t;
    while (t--) {
        cin >> n >> res;
        fill(isVisit, isVisit + 10001false); // 방문여부 초기화
        q = queue<struct n>(); // 큐 클리어(초기화)
        solve(n, res);
    }
}​
cs
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
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
글 보관함