http://www.spoj.com/problems/POUR1/
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.
Input
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.
Output
For each set of input data, output the minimum number of steps required to obtain c litres, or -1 if this is impossible.
Example
Sample input:
Sample output:
http://rchardx.is-programmer.com/posts/16699.html2 5 2 3 2 3 4
2 -1
int ntest,a,b,c,d; int min( int a, int b) { return a<b?a:b; } int gcd( int a, int b) { return b==0?a:gcd(b,a%b); } int check( int a, int b) { int ret = 0,ca = 0,cb = 0; for (;;) { if (ca==c || cb==c) return ret; if (cb==b) cb = 0; else if (ca==0) ca = a; else { int dt = min(b-cb,ca); ca -= dt; cb += dt; } ret++; } } int main() { scanf ( "%d" ,&ntest); while (ntest--) { scanf ( "%d%d%d" ,&a,&b,&c); d = gcd(a,b); if (c%d!=0 || c>a && c>b) printf ( "-1\n" ); else { int ans = check(a,b); ans = min(ans,check(b,a)); printf ( "%d\n" ,ans); } } return 0; } |