-
[14395] 4연산BOJ 2021. 11. 9. 14:15
https://www.acmicpc.net/problem/14395
14395번: 4연산
첫째 줄에 정수 s를 t로 바꾸는 방법을 출력한다. s와 t가 같은 경우에는 0을, 바꿀 수 없는 경우에는 -1을 출력한다. 가능한 방법이 여러 가지라면, 사전 순으로 앞서는 것을 출력한다. 연산의 아
www.acmicpc.net
<문제>
먼저, '-'연산은 전혀 의미가없다. 수행하면 0이되는데 0에서 다른 정점으로 갈 방법이 없고, 종료정점은 1 이상이다.
1e9만큼 bool형을 만들순 없지만, 가능한 정점의 폭에 비해 방문하는 정점의 개수가 꽤 작다.
set을 사용하여 방문처리를 진행해주고, 10억*10억>INT_MAX이므로 일시적으로 long long을 사용해준다.
<소스코드>
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849#include <bits/stdc++.h>using namespace std;const int MAX = 1e9;typedef long long ll;typedef struct {ll n;string op;} state;queue<state> q;set<ll> s;ll x, y;int main(void) {cin >> x >> y;if (x == y) {cout << 0;return 0;}q.push({x, ""});s.insert(x);while (!q.empty()) {auto cur = q.front();q.pop();if (cur.n == y) {cout << cur.op;return 0;}ll temp = cur.n;if (temp * temp <= MAX) {ll next = temp * temp;if (s.find(next) == s.end()) {s.insert(next);q.push({next, cur.op + "*"});}}if (temp + temp <= MAX) {ll next = temp + temp;if (s.find(next) == s.end()) {s.insert(next);q.push({next, cur.op + "+"});}}if (s.find(1) == s.end()) {s.insert(1);q.push({1, cur.op + "/"});}}cout << -1;return 0;}cs 'BOJ' 카테고리의 다른 글
[17503] 맥주 축제 (0) 2021.11.10 [13975] 파일 합치기 3 (0) 2021.11.09 [16973] 직사각형 탈출 (0) 2021.11.09 [14940] 쉬운 최단거리 (0) 2021.11.09 [15971] 두 로봇 (0) 2021.11.09