It is not difficult to solve the problem of buying chicken, the key is that it has been upgraded, the test data is too large, the traditional solution, such as Triple loop, double cycle will lead to timeouts.
The correct solution to this problem should be to combine the mathematical equation to simplify and convert it into a 1-layer loop:
X+y+z=n
Ax+by+c/d*z=m
By the above two equations can be used to represent the other amount of Y. This solves the problem by simply enumerating the X.
After solving the equation, be careful to simplify, and divide evenly only when you can divide it evenly. Finally, when compared with m because of the problem of C/D, so the equation is multiplied by D to eliminate the error .
Finally do not add z%d==0 conditions, because for example, when 3 yuan to buy 12 chicks, the reality is that at least four chickens are legal circumstances will not appear, but z%12 will become a minimum buy 12 chickens is the legal situation, so should remove this condition.
1#include <stdio.h>2 intMain () {3 Chars[ -];4 Long LongA , B, C, D, M, N;5 gets (s); 6 intfirst=0;7 intOK;8 intk=0;9 while(SCANF ("%lld,%lld,%lld/%lld,%lld,%lld", &a,&b,&c,&d,&m,&n)! =EOF) {Tenk++; One if(first==0) first=1;Elseprintf"\ n"); Aok=0; - for(Long LongI=0; i<=m/a;i++){ - Long LongJ; the if((m*d-c*n-(a*d-c) *i)% (b*d-c) = =0) -J= (m*d-c*n-(a*d-c) *i)/(b*d-c); - if(j<0)Continue; - Long Longz=n-i-J; + if((z*c+i*a*d+j*b*d) ==m*d&&z>=0){ - if(!ok) printf ("cocks,hens,chicks\n"); +ok=1; Aprintf"%lld,%lld,%lld\n", i,j,z); at } - } - if(!ok) printf ("cannot buy!\n"); - - } - return 0; in}
Sdust Software Engineering 2016-homework 4-a hundred money buy chicken problem