[BOJ] 9019번 DSLR - C++

"동적 계획법과 최단거리 역추적"

Posted by Yongmin on August 13, 2021

문제

DSLR

풀이

BFS를 이용한 문제이다. 값들과 string을 pair로 하여 queue에 저장하는 식으로 문제를 접근하였다. Reference에서 코드를 가져왔다. 네 자리수를 왼쪽과 오른쪽으로 이동하는 방법을 기억해두면 좋을 것 같다. 왼쪽으로 이동 : nx = (x % 1000) * 10 + (x / 1000); 오른쪽으로 이동 : nx = (x % 10) * 1000 + (x / 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
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include<iostream>
#include<cstring>
#include<string>
#include<queue>
 
#define endl "\n"
#define MAX 10000
using namespace std;
 
int Start, End;
bool Visit[MAX];
 
void Initialize()
{
    memset(Visit, false, sizeof(Visit));
}
 
void Input()
{
    cin >> Start >> End;
}
 
string BFS(int a)
{
    queue<pair<int, string>> Q;
    Q.push(make_pair(a, ""));
    Visit[a] = true;
 
    while (Q.empty() == 0)
    {
        int x = Q.front().first;
        string s = Q.front().second;
        Q.pop();
 
        if (x == End) return s;
        
        int nx = x * 2;
        if (nx > 9999) nx = nx % 10000;
        if (Visit[nx] == false)
        {
            Visit[nx] = true;
            Q.push(make_pair(nx, s + "D"));
        }
 
        nx = x - 1;
        if (nx < 0) nx = 9999;
        if (Visit[nx] == false)
        {
            Visit[nx] = true;
            Q.push(make_pair(nx, s + "S"));
        }
 
        nx = (x % 1000) * 10 + (x / 1000);
        if (Visit[nx] == false)
        {
            Visit[nx] = true;
            Q.push(make_pair(nx, s + "L"));
        }
 
        nx = (x % 10) * 1000 + (x / 10);
        if (Visit[nx] == false)
        {
            Visit[nx] = true;
            Q.push(make_pair(nx, s + "R"));
        }
    }
}
 
 
void Solution()
{
    string R = BFS(Start);
    cout << R << endl;
}
 
void Solve()
{
    int Tc;
    cin >> Tc;
    for (int T = 1; T <= Tc; T++)
    {
        Initialize();
        Input();
        Solution();
    }
}
 
int main(void)
{
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
 
    //freopen("Input.txt", "r", stdin);
    Solve();
 
    return 0;
}


//출처: https://yabmoons.tistory.com/70 [얍문's Coding World..]


# # #