그래프/BFS
물통
4gats
2023. 9. 1. 13:54
https://www.acmicpc.net/problem/2251
2251번: 물통
각각 부피가 A, B, C(1≤A, B, C≤200) 리터인 세 개의 물통이 있다. 처음에는 앞의 두 물통은 비어 있고, 세 번째 물통은 가득(C 리터) 차 있다. 이제 어떤 물통에 들어있는 물을 다른 물통으로 쏟아 부
www.acmicpc.net
숨바꼭질, DSLR 문제와 유사하다.
각 단계를 노드라고 생각하는 것.
물을 옮기는 방법은 6가지 있다.
그에 따른 send, receive 배열을 만들어서
BFS를 돌리자.
visited 배열은 삼차원이 필요가 없다.
물의 양은 정해져 있기 때문!
이차원 배열을 만들고
C = now[2] - A - B 하면 됨.
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
|
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
// 물통 번호 0, 1, 2
int send[] = { 0, 0, 1, 1, 2, 2 };
int receive[] = { 1, 2, 0, 2, 0, 1 };
// 3차원 배열을 쓰는 게 아니라
// A, B의 용량이 있으면 C의 용량이 고정
bool visited[201][201];
bool answer[201];
int now[3];
void BFS()
{
queue<pair<int, int>> q;
q.push(make_pair(0, 0));
visited[0][0] = true;
// 처음에 A는 비어있으니
answer[now[2]] = true;
while (!q.empty())
{
int A = q.front().first;
int B = q.front().second;
int C = now[2] - A - B;
q.pop();
for (int k = 0; k < 6; k++)
{
int next[] = { A, B, C };
next[receive[k]] += next[send[k]];
next[send[k]] = 0;
// 대상 물통의 용량ㅂ다 물이 많을 때
if (next[receive[k]] > now[receive[k]])
{
// 초과하는 만큼 다시 이전 물통에 넣음
next[send[k]] = next[receive[k]] - now[receive[k]];
// 대상 물통은 최대로 채움
next[receive[k]] = now[receive[k]];
}
if (!visited[next[0]][next[1]])
{
visited[next[0]][next[1]] = true;
q.push(make_pair(next[0], next[1]));
if (next[0] == 0)
answer[next[2]] = true;
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> now[0] >> now[1] >> now[2];
BFS();
for (int i = 0; i <= now[2]; i++)
{
if (answer[i])
cout << i << ' ';
}
return 0;
}
|
cs |