Hyemi Lee

Hyemi Lee

주니어 개발자의 삽질과 기록

Algorithm, boj, 물통(2251)

물통

풀이

1. A , B , C 물통이 있을때 물이 담겨있는 한가지 상황에 대해
여섯가지 방법으로 물을 따라서 상황을 바꿀수있다.
A -> B
A -> C
B -> A
B -> C
C -> A
C -> B
2. 새로 생겨난 상황이 이전에도 있었는지 HashSet을 이용해서 확인하고
3. 처음 보는 상황이라면 Queue에 넣어
다시 6가지 방법으로 따라본다.
4. Queue가 빌때까지 반복한다.

핵심

  • 한가지 상황에 대해서 상황이 어떻게 바뀔수 있는지를 알아야 한다.
  • 바뀐 상황이 새로운 상황이면 큐에 삽입

코드

package org.baekjoon;
import java.util.*;
public class test2251_waterBottle {
	static int a, b, c;
	static Queue<int[]> q;
	static HashSet<String> hs;
	static int[] origin;
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		origin = new int[3];
		for (int i = 0; i < 3; i++) {
			origin[i] = sc.nextInt();
		}
		q = new LinkedList<>();
		hs = new HashSet<>();
		int[] first = {0,0,origin[2]};
		q.offer(first);
		bfs();
	}
	private static void bfs() {
		List<Integer> list = new ArrayList<>();
		while (!q.isEmpty()) {
			int[] bottle = q.poll();
			if (bottle[0] == 0)
				list.add(bottle[2]);
			for (int give = 0; give < 3; give++) {
				for (int j = 1; j < 3; j++) {
					int[] newBottle = bottle.clone();
					int receive = (give + j) % 3;
					// 줄수없으면 변화가 없으므로 패쓰.
					// 줄수있는게 0 ᄋ이거나 받을수있는게 0
					if (bottle[give] == 0 || bottle[receive] == origin[receive])
						continue;
					if (bottle[give]+bottle[receive] > origin[receive]) {
						newBottle[give] = bottle[give] - (origin[receive]-newBottle[receive]);
						newBottle[receive] = origin[receive];
					}else {
						newBottle[receive] += bottle[give];
						newBottle[give] = 0;
					}
					String str = "";
					for(Integer b : newBottle) {
						str += b;
					}
					if(!hs.contains(str)) {
						q.offer(newBottle);
						hs.add(str);
					}
				}
			}
		}
		Collections.sort(list);
		for(int i=0; i<list.size()-1; i++)
			System.out.print(list.get(i)+" ");
	}
}

비슷한 문제 - 돌그룹(12886)

Share on

Twitter Facebook LinkedIn

You may also enjoy

Redis Stream

2021年04月28日

Stream Stream은 로그 데이터를 처리하게위해 5.0에서 새로 도입된 데이터 타입입니다. 대량의 데이터가 연속적으로 발생할때 처리하기 위해 등장했습니다. 기존 데이터를 수정하지 않고 오직 추가로 발생합니다. 이런 종류의 데이터를 stream or log데이터...

Study, Object, chapter2&3 presentation

2021年04月20日

chapter03. 역할, 책임, 협력 객체지향 설계란, 올바른 객체에게 올바른 책임을 할당하면서 낮은 결합도와 높은 응집도를 가진 구조를 창조하는 활동이다.

Spring, chatting 프로그램 만들기, Reactive란?

2020年06月16日

Reactive 막힘없이 흘러다니는 data(event)를 통해 사용자에게 자연스러운 응답을 주고 규모 탄력적으로 리소스를 사용하며 실패에 있어서 유연하게 대처한다 모든 지점에서 블럭 되지 않게 하자 oop와 같은 패러다임 모든 것을 비동기적인 data의 strea...