-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathFilling_Cans_Problem.c
More file actions
100 lines (87 loc) · 1.5 KB
/
Filling_Cans_Problem.c
File metadata and controls
100 lines (87 loc) · 1.5 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
* Filling Cans
* ------------
*
* Two cans are with capacity X and y liters.
* The program must determine the number of steps required to obtain exactly Z liters
* of liquid one of the cans.
*
* At the beginning both the cans are empty.The following operations are countered as “steps”:
*
* ->emptying a vessel
* ->filling a vessel
* ->pouring liquid from larger can to the smaller,
* without spilling untill one of the cans is either full or empty.
*
* If it is not possible to obtain Z liters exactly then the output must be -1.
*
* Example 1:
*
* Input:
* 5
* 2
* 3
* Output:
* 2
*
* Explanation:
* Here X=5,Y=2
* Step 1:Pour 5 liters of liquid into 5 liter can
* step 2:Pour 2 liter from 5 liter can into 2 liter can
* Now the 5 liter can will have 3 liter which is Z.Hence 2 steps are required.
*
* Example 2:
*
* Input:
* 2
* 3
* 4
* Output:
* -1
*
* Explanation:
* Z is greater than X and Y.
* Hence it is not possible to have 4 liters in any one of the cans.
* Hence output is -1.
*
*/
#include <stdio.h>
int main()
{
int x, y, z;
int count = 1, check = 0, res = 0;
scanf("%d %d %d",&x,&y,&z);
if( z > x && z > y )
{
printf("%d",-1);
return 0;
}
if( x < y )
{
int temp = x;
x = y;
y = temp;
}
else{
do
{
if( x == z )
{
check = 1;
break;
}
x = x-y;
if( res )
{
count += 2;
}
else
{
count++;
res = 1;
}
}while( x >= z );
}
printf("%d", (check) ? count : -1 );
return 0;
}