티스토리 뷰

Algorithm/BOJ

9019 DSLR

henry1214 2018. 3. 14. 16:40

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



정수 A에서 D,S,L,R 연산을 쓰면서 정수 B를 만드려고 할 때 최소 연산 횟수를 구하는 문제이다. BFS로 구할 수 있다. 큐에 (int 정수,string 지금까지 쓴 명령어)를 넣으면서 답을 찾는다.



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
#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <queue>
using namespace std;
 
int a,b;
bool visit[10001];
 
void bfs()
{
    queue<pair<int,string>> q;
    q.push({a,""});
    visit[a]=true;
 
    while(!q.empty())
    {
        auto now=q.front(); q.pop();
        int n=now.first;
        string t=now.second;
 
        if(n==b)
        {
            cout<<t<<'\n';
            return;
        }
 
        // D 명령어 수행
        int next=2*n;
        if(2*n>9999) next=(2*n)%10000;
        if(!visit[next])
        {
            visit[next]=true;
            q.push({next,t+"D"});
        }
 
        // S 명령어 수행
        if(n==0) next=9999;
        else next=n-1;
        if(!visit[next])
        {
            visit[next]=true;
            q.push({next,t+"S"});
        }
 
        // 각 자리수 구하기
        int temp=n;
        int d[4];
        for(int i=3;i>=0;i--)
        {
            d[i]=temp%10;
            temp/=10;
        }
 
        // L 명령어 수행
        next=d[1]*1000+d[2]*100+d[3]*10+d[0];
        if(!visit[next])
        {
            visit[next]=true;
            q.push({next,t+"L"});
        }
 
        // R 명령어 수행
        next=d[3]*1000+d[0]*100+d[1]*10+d[2];
        if(!visit[next])
        {
            visit[next]=true;
            q.push({next,t+"R"});
        }
    }
}
 
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d %d",&a,&b);
        bfs();
        memset(visit,0,sizeof(visit));
    }
    return 0;
}
cs


'Algorithm > BOJ' 카테고리의 다른 글

2138 전구와 스위치  (0) 2018.03.14
2573 빙산  (0) 2018.03.14
1600 말이 되고픈 원숭이  (0) 2018.03.14
11444 피보나치 수 6  (0) 2018.03.08
2749 피보나치 수 3  (0) 2018.03.08
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday