uva 10090 二元一次不定方程

Marbles

Input: standard input

Output: standard output

I have some (say, n) marbles (small glass balls) and I am going to buy some boxes to store them. The boxes are of two types:

Type 1: each box costs c1 Taka and can hold exactly n1 marbles

Type 2: each box costs c2 Taka and can hold exactly n2 marbles

I want each of the used boxes to be filled to its capacity and also to minimize the total cost of buying them. Since I find it difficult for me to figure out how to distribute my marbles among the boxes, I seek your help. I want your program to be efficient also.

Input

The input file may contain multiple test cases. Each test case begins with a line containing the integer n (1 <= n <= 2,000,000,000). The second line contains c1 and n1, and the third line contains c2 and n2. Here, c1c2n1 and nare all positive integers having values smaller than 2,000,000,000.

A test case containing a zero for n in the first line terminates the input.

Output

For each test case in the input print a line containing the minimum cost solution (two nonnegative integers m1 and m2, where mi = number of Type i boxes required) if one exists, print "failed" otherwise.

If a solution exists, you may assume that it is unique.

 

Sample Input

43 1 3 2 4 40 5 9 5 12 0

 

Sample Output

13 1 failed

AC代码:

#include<iostream>
#include<cstdio>
using namespace std;

long long Extended_Euclid(long long a,long long b,long long &x,long long &y)
{
    long long t,d;
    if(!b)
    {
        x=1;y=0;
        return a;
    }
    d=Extended_Euclid(b,a%b,x,y);
    t=x;
    x=y;
    y=t-a/b*y;
    return d;
}

int main()
{
    long long n,c1,n1,c2,n2,x,y,d,x1,y1,min,tx,ty;
    while(scanf("%lld",&n),n)
    {
        scanf("%lld %lld %lld %lld",&c1,&n1,&c2,&n2);
        d=Extended_Euclid(n1,n2,x,y);
        if(n%d==0)
        {
            n1/=d;
            n2/=d;
            n/=d;
            x=x*n;
            y=y*n;
            x1=(x%n2+n2)%n2;
            y1=(n-x1*n1)/n2;
            tx=x1;
            ty=y1;
            min=-1;
            if (y1 >= 0)
               min = (x1*c1 + y1*c2) ;
            y1=(y%n1+n1)%n1;
            x1=(n-n2*y1)/n1;
             if ((min > x1*c1 + y1*c2 || min == -1) && x1 >= 0)
            {
               tx = x1 ;
               ty = y1 ;
            }
            if(min!=-1)
                printf("%lld %lld
",tx,ty);
            else
                printf("failed
");
        }
        else
            printf("failed
");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/xiong-/p/3222487.html