문제 출처 : https://www.acmicpc.net/problem/14395
14395번: 4연산
첫째 줄에 정수 s를 t로 바꾸는 방법을 출력한다. s와 t가 같은 경우에는 0을, 바꿀 수 없는 경우에는 -1을 출력한다. 가능한 방법이 여러 가지라면, 사전 순으로 앞서는 것을 출력한다. 연산의 아스키 코드 순서는 '*', '+', '-', '/' 이다.
www.acmicpc.net
1) 10억이 넘는 배열은 못 만듦 -> set, map을 활용한다
2) bfs을 해준다.
<c++>
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 86 87 | #include<iostream> #include<set> #include<queue> #include<map> #include<algorithm> #define MAX 1000000001 using namespace std; set<long long > se; map<long long,char > ma; map<long long,long long > t; string temp; int main(void) { long long n,m; cin>>n>>m; if(n==m) { cout<<0<<endl; return 0; } queue<pair<long long ,long long > > q; q.push({n,0}); se.insert(n); // set<long long > ::iterator iter; while(!q.empty()) { long long x=q.front().first; long long cnt=q.front().second; q.pop(); if(x==m) { // cout<<cnt<<endl; temp+=ma[x]; int s=t[x]; while(cnt--!=1) { temp+=ma[s]; s=t[s]; } reverse(temp.begin(),temp.end()); cout<<temp<<endl; } long long next=x*x; if(next<=1000000000&&se.find(next)==se.end()) { se.insert(next); q.push({next,cnt+1}); ma[next]='*'; t[next]=x; } next=x+x; if(next<=1000000000&&se.find(next)==se.end()) { se.insert(next); q.push({next,cnt+1}); ma[next]='+'; t[next]=x; } next=x-x; if(next>=1&&se.find(next)==se.end()) { se.insert(next); q.push({next,cnt+1}); ma[next]='-'; t[next]=x; } next=x/x; if(next>=1&&se.find(next)==se.end()) { se.insert(next); q.push({next,cnt+1}); ma[next]='/'; t[next]=x; } } if(se.find(m)==se.end()) { cout<<-1<<endl; } return 0; } | cs |
'백준 온라인 저지 > BFS, DFS (그래프)' 카테고리의 다른 글
6087번_레이저 통신 (0) | 2020.02.26 |
---|---|
적록색약_10026번 (0) | 2020.02.26 |
16954번_움직이는 미로 탈출 (0) | 2020.02.20 |
16928번_뱀과 사다리 게임 (0) | 2020.02.19 |
16948번_데스 나이트 (0) | 2020.02.19 |