POUR1 - Pouring water

Given two vessels, one of which can accommodate a litres of water and the other - b litres of water, determine the number of steps required to obtain exactly c litres of water in one of the vessels.

At the beginning both vessels are empty. The following operations are counted as 'steps':

  • emptying a vessel,
  • filling a vessel,
  • pouring water from one vessel to the other, without spilling, until one of the vessels is either full or empty.



An integer t, 1<=t<=100, denoting the number of testcases, followed by t sets of input data, each consisting of three positive integers a, b, c, not larger than 40000, given in separate lines.


For each set of input data, output the minimum number of steps required to obtain c litres, or -1 if this is impossible.


Sample input:


Sample output:

hide comments
karan_yadav: 2018-07-12 12:04:40

Was searching for a better solution online (I used DP). After searching for a bit found a really elegant yet simple solution on StackOverflow, (https://stackoverflow.com/questions/17869493/advice-for-pour1-on-spoj)
Do give it a read.

mahabir10: 2018-06-13 16:28:54

i got accepted using only map and bfs

sherlock11: 2018-05-16 10:21:37

bfs will work...........but carefully examine when answer will be "-1"........otherwise enjoy "TLE"

itzsowvik: 2018-05-08 17:47:12

Isn't this problem is too much hard for beginners?

nadino: 2018-04-30 10:42:18


for those who are using Java and don't want a TLE

gauravgb21: 2018-04-25 17:06:32

solved it using DP!

chetan4060: 2017-12-28 12:38:51

ad-hoc problem
just see the pattern and read about
Diophantine equation ax+by = c .

vengatesh15: 2017-12-21 11:08:34

easy BFS

chachaji_harsh: 2017-12-04 17:35:45

how is it a DP problem

mahilewets: 2017-08-29 20:18:26

I think BFS is bad here

Because 40000 limitation

If limitation is like 255

We can easily afford BFS even with three vessels

Added by:adrian
Time limit:1s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: NODEJS PERL6 VB.NET
Resource:An ancient problem, formulated in these words by Mr Tadeusz Ratajczak