알고리즘
백준 14395번 4연산 C++
영춘권의달인
2022. 11. 21. 14:31
https://www.acmicpc.net/problem/14395
14395번: 4연산
첫째 줄에 정수 s를 t로 바꾸는 방법을 출력한다. s와 t가 같은 경우에는 0을, 바꿀 수 없는 경우에는 -1을 출력한다. 가능한 방법이 여러 가지라면, 사전 순으로 앞서는 것을 출력한다. 연산의 아
www.acmicpc.net
bfs
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <limits.h>
using namespace std;
using int64 = long long;
int64 s, t;
struct Info {
int64 val;
string ops;
};
set<int64> st;
char op[4] = { '*','+','-','/' };
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> s >> t;
queue<Info> q;
string ans = "?";
q.push({ s,"" });
st.insert(s);
while (!q.empty()) {
auto curr = q.front();
q.pop();
if (curr.val == t) {
ans = curr.ops;
break;
}
for (int i = 0; i < 4; i++) {
char nextOp = op[i];
int64 nextVal = curr.val;
switch (nextOp) {
case '*':
nextVal *= curr.val;
break;
case '+':
nextVal += curr.val;
break;
case '-':
nextVal -= curr.val;
break;
case '/':
if (curr.val != 0) {
nextVal /= curr.val;
}
break;
}
if (st.find(nextVal) != st.end()) continue;
q.push({ nextVal,curr.ops + nextOp });
st.insert(nextVal);
}
}
if (ans == "") cout << 0;
else if (ans == "?") cout << -1;
else cout << ans;
}