알고리즘/문제 풀이

백준 9019 - DSLR(C++)

qqlzzb 2023. 11. 23. 11:34

문제

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

 

9019번: DSLR

네 개의 명령어 D, S, L, R 을 이용하는 간단한 계산기가 있다. 이 계산기에는 레지스터가 하나 있는데, 이 레지스터에는 0 이상 10,000 미만의 십진수를 저장할 수 있다. 각 명령어는 이 레지스터에

www.acmicpc.net

 

풀이

처음 생각한 방식은

#include <iostream>
#include <queue>

using namespace std;
int a, b;

void bfs() {
    queue<pair<int, string>> q;
    q.push({a, ""});

    while (!q.empty()) {
        int tmp;
        int x = q.front().first;
        string op = q.front().second;
        q.pop();

        if (x == b) {
            cout << op << '\n';
            return;
        }

        tmp = (2 * x) % 10000; // D
        q.push({tmp, op + "D"});

        tmp = x - 1; // S
        if (tmp == -1) tmp = 9999;
        q.push({tmp, op + "S"});

        tmp = (x % 1000) * 10 + x / 1000; // L
        q.push({tmp, op + "L"});

        tmp = (x % 10) * 1000 + x / 10; // R
        q.push({tmp, op + "R"});

    }
}

int main() {
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> a >> b;
        bfs();
    }
}

각 연산 결과마다 DSLR 연산해 주면 되겠다고 생각했고,

방문체크 없이 연산한 모든 숫자를 큐에 넣어줘도 된다고 생각했음

하지만 메모리 초과. 방문한 숫자는 표시해줘야 함

 

queue<pair<int, string>> q;
q.push({a, ""});
visited[a]= true;

while (!q.empty()) {
    int tmp;
    int x = q.front().first;
    string op = q.front().second;
    q.pop();

    if (x == b) {
        cout << op << '\n';
        return;
    }
}

이렇게 큐에 숫자랑 연산 내역을 같이 저장하는 것을 생각을 못해서 헤맸다..

이것만 생각해낼 수 있었으면 은근히 쉽게 풀 수 있었을 듯 ㅜㅜ

 

코드

#include <iostream>
#include <queue>

using namespace std;
int a, b;
bool visited[10000];

void bfs() {
    queue<pair<int, string>> q;
    q.push({a, ""});
    visited[a]= true;

    while (!q.empty()) {
        int tmp;
        int x = q.front().first;
        string op = q.front().second;
        q.pop();

        if (x == b) {
            cout << op << '\n';
            return;
        }

        tmp = (2 * x) % 10000;
        if(!visited[tmp]) {
            visited[tmp]= true;
            q.push({tmp, op + "D"});
        }

        tmp = x - 1;
        if (tmp == -1) tmp = 9999;
        if(!visited[tmp]) {
            visited[tmp]= true;
            q.push({tmp, op + "S"});
        }

        tmp = (x % 1000) * 10 + x / 1000;
        if(!visited[tmp]) {
            visited[tmp]= true;
            q.push({tmp, op + "L"});
        }

        tmp = (x % 10) * 1000 + x / 10;
        if(!visited[tmp]) {
            visited[tmp]= true;
            q.push({tmp, op + "R"});
        }

    }
}

int main() {
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> a >> b;
        bfs();
        fill_n(visited,10000,false);
    }
}

'알고리즘 > 문제 풀이' 카테고리의 다른 글

백준 11404 - 플로이드(C++)  (1) 2023.11.28
Problem 1600 - 말이 되고픈 원숭이(C++)  (1) 2023.11.24
백준 2504 - 괄호의 값(C++)  (0) 2023.04.28
백준 11292 - 키 큰 사람(C++)  (0) 2022.12.04
백준 4470 - 줄번호  (0) 2022.11.17