๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 14395_4์—ฐ์‚ฐ

๋ฟŒ์•ผ._. 2023. 3. 5. 23:16

Gold V

๋ฌธ์ œ(์ถœ์ฒ˜: 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 ์“ธ ์ƒ๊ฐ์„ ์™œ ๋ชปํ–ˆ๋Š”์ง€.. ๋” ๋ถ„๋ฐœํ•˜์ž