๋ฌธ์ (์ถ์ฒ: https://www.acmicpc.net/problem/14395)
< 4์ฐ์ฐ >
๋ฌธ์  ํ์ด
bfs๋ฅผ ํ์ฉํ์ฌ s๋ฅผ t๋ก ๋ฐ๊พธ๋ ๋ฐฉ๋ฒ์ ์ฐพ์๋ค.
์ฒ์์๋ ๋ฐฉ๋ฌธ ๋ฐฐ์ด์ ์ฌ์ฉํ๋ ค ํ์ง๋ง ๋ฒ์๊ฐ ๋์ด๊ฐ ์๋ฌ๊ฐ ๋ฐ์ํ์๋ค. ์ฐพ์๋ณด๋ ๊ทธ๋์ ์ฌ๋๋ค์ด set์ ์ฐ๋ ๊ฑฐ์๋ค.
set์ ํ์ฉํ์ฌ ์ค๋ณต ํ์ธ์ ํ์ฌ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ ์ ์์๋ค.
- my solution (Java)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class _14395_ { // 4์ฐ์ฐ
	public static void main(String[] args) throws IOException {
		BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer(bf.readLine());
		long s=Integer.parseInt(st.nextToken());
		long t=Integer.parseInt(st.nextToken());
		HashSet<Long>set=new HashSet<>();
		String result="";
		// s์ t๊ฐ ๊ฐ์ ๊ฒฝ์ฐ
		if(s==t) System.out.println(0);
		else { // s์ t๊ฐ ๋ค๋ฅธ ๊ฒฝ์ฐ
			Queue<Info>queue=new LinkedList<>();
			queue.add(new Info(s, ""));
			set.add(s);
			while(!queue.isEmpty()) {
				Info info=queue.poll();
				long arr[]= {info.value*info.value,info.value+info.value, 0, 1}; // *, +, -, /
				for(int i=0; i<4; i++) {
					if(!set.contains(arr[i])) {
						String str=info.cal;
						if(i==3 && info.value==0) break;
						if(i==0)str+="*";
						else if(i==1) str+="+";
						else if(i==2) str+="-";
						else if(i==3) str+="/";
						if(arr[i]==t) {
							result=str;
							break;
						}
						set.add(arr[i]);
						queue.add(new Info(arr[i], str));
					}
				}
				if(!result.equals("")) break;
			}
			if(result.equals("")) System.out.println(-1); // ๋ฐ๊ฟ ์ ์๋ ๊ฒฝ์ฐ
			else System.out.println(result);
		}
	}
	static class Info{
		long value; // ๊ฐ
		String cal; // ๋ฐฉ๋ฒ
		public Info(long value, String cal) {
			this.value=value;
			this.cal=cal;
		}
	}
}
Main
- s์ t ์ ๋ ฅ
- set : ์ค๋ณต ์ฌ๋ถ๋ฅผ ํ๋ณํ๊ธฐ ์ํด Hashset ์ ์ธ
- s์ t๊ฐ ๊ฐ์ ๊ฒฝ์ฐ 0 ์ถ๋ ฅ
- s์ t๊ฐ ๋ค๋ฅธ ๊ฒฝ์ฐ bfs ํ์ -> queue๊ฐ ๋น ๋๊น์ง ๋ฐ๋ณตํ์ฌ *, +, -, / ์์ผ๋ก ์ฐ์ฐํ์ฌ ์์ง set์ ์๋ ๊ฐ์ด๋ฉด set๊ณผ queue์ ๋ฃ์ด์ฃผ๊ธฐ -> t๋ก ๋ฐ๊ฟจ์ผ๋ฉด ์ข ๋ฃ
- ๋ฐ๊ฟ ์ ์๋ ๊ฒฝ์ฐ์๋ -1 ์ถ๋ ฅ, ๋ฐ๊พผ ๊ฒฝ์ฐ์๋ result ์ถ๋ ฅ
์๊ฐ๐ค
visited ๋ฒ์ ๋๋ฌธ์ ์๋ฌ๊ฐ ๋ฌ๋ ๊ฒ ๊ฐ๋ค... set ์ธ ์๊ฐ์ ์ ๋ชปํ๋์ง.. ๋ ๋ถ๋ฐํ์

'๐Algorithm > ๐ฅBaekjoon' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [Baekjoon] 17129_์๋ฆฌ์์จ์์ก๋นจ์ด๋ฑ๋ฐ๊ตฌ๋ฆฌ๊ฐ ์ ๋ณด์ฌ์ ์ฌ๋ผ์จ ์ด์ (0) | 2023.03.09 | 
|---|---|
| [Baekjoon] 15558_์ ํ ๊ฒ์ (0) | 2023.03.09 | 
| [Baekjoon] 12761_๋๋ค๋ฆฌ (0) | 2023.03.03 | 
| [Baekjoon] 11123_์ ํ๋ง๋ฆฌ... ์ ๋๋ง๋ฆฌ... (0) | 2023.03.01 | 
| [Baekjoon] 14940_์ฌ์ด ์ต๋จ๊ฑฐ๋ฆฌ (0) | 2023.02.27 |