Sdust Software Engineering 2016-homework 4-a hundred money buy chicken problem

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.