문제 링크입니다: https://www.acmicpc.net/problem/14395
14395번: 4연산
첫째 줄에 정수 s를 t로 바꾸는 방법을 출력한다. s와 t가 같은 경우에는 0을, 바꿀 수 없는 경우에는 -1을 출력한다. 가능한 방법이 여러 가지라면, 사전 순으로 앞서는 것을 출력한다. 연산의 아스키 코드 순서는 '*', '+', '-', '/' 이다.
www.acmicpc.net
사칙연산의 우선순위가 있기 때문에 *, +, / 순으로 큐에 Node를 push 하도록 코드를 작성했습니다.
- 같은 경우 s, t 모두 0이 될 수 없으므로 로직에 포함시키지 않았습니다.
중복된 s를 계산하지 않기 위해 map을 사용했고 각 과정을 Node 구조체의 process 문자열에 저장했습니다.
마지막으로 / 같은 경우 1은 한번만 등장하면 되기 때문에 별도의 boolean 변수 flag를 이용하여 한번만 계산하도록 했습니다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <queue> | |
#include <map> | |
using namespace std; | |
typedef struct | |
{ | |
long long s; | |
string process; | |
} Node; | |
map<long long, bool> visited; | |
int main(void) | |
{ | |
ios_base::sync_with_stdio(0); | |
cin.tie(0); | |
long long s, t; | |
cin >> s >> t; | |
if (s == t) | |
{ | |
cout << 0 << "\n"; | |
return 0; | |
} | |
queue<Node> q; | |
q.push({ s, "" }); | |
bool flag = true; | |
while (!q.empty()) | |
{ | |
int qSize = q.size(); | |
for (int i = 0; i < qSize; i++) | |
{ | |
Node node = q.front(); | |
q.pop(); | |
if (node.s == t) | |
{ | |
cout << node.process << "\n"; | |
return 0; | |
} | |
long long temp = node.s * node.s; | |
if (temp <= t && visited.count(temp) == false) | |
{ | |
q.push({ temp, node.process + '*' }); | |
visited[temp] = true; | |
} | |
temp = node.s * 2; | |
if (temp <= t && visited.count(temp) == false) | |
{ | |
q.push({ temp, node.process + '+' }); | |
} | |
if (flag) | |
{ | |
q.push({ 1, node.process + '/' }); | |
flag = false; | |
} | |
} | |
} | |
cout << -1 << "\n"; | |
return 0; | |
} |


개발환경:Visual Studio 2017
지적, 조언, 질문 환영입니다! 댓글 남겨주세요~
반응형
'알고리즘 > BOJ' 카테고리의 다른 글
백준 9322번 철벽 보안 알고리즘 (0) | 2020.02.19 |
---|---|
백준 16673번 고려대학교에는 공식 와인이 있다 (0) | 2020.02.18 |
백준 2941번 크로아티아 알파벳 (0) | 2020.02.16 |
백준 15970번 화살표 그리기 (0) | 2020.02.14 |
백준 5639번 이진 검색 트리 (2) | 2020.02.07 |