SDAU数论练习五F(扩展欧几里得)

On one of the Caribbean Islands there are N tourists and you want to move them from this island to another one.

There are only two boats on this island, the first one can hold n1 tourists and cost c1 to move exactly n1 tourists from one Island to another, and the second one can hold n2 and cost c2.

The boat will not sail unless it is fully booked. Moreover, you want to minimize the total cost of moving all tourists from one island to another. You can use any boat several times.

Input

The input may contain multiple test cases. Each test case begins with a line containing an integer N (1 ≤ N ≤ 2 * 109).

The second line contains c1 and n1, and the third line contains c2 and n2.

Here, c1, c2, n1 and n2 are all positive integers having values smaller than 2 * 109.

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 non-negative integers m1 and m2, where m1 is the number of times to use the first boat, and m2 is the number of times to use the second boat) if one exists.

Print "failed" otherwise. If a solution exists, you may assume that it is unique.

Examples

Input

43
1 3
2 4
40
5 9
5 12
0

Output

13 1
failed

 

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
using namespace std;
typedef long long LL;
LL exgcd(LL a,LL b,LL &x,LL &y)
{
    if(b==0)
    {
        x=1,y=0;
        return a;
    }
    LL d=exgcd(b,a%b,x,y);
    LL z=x;
    x=y;
    y=z-y*(a/b);
    return d;
}
LL solve(LL a,LL b,LL c)//扩展欧几里得是ax+cy=b,线性同余是ax=b%c.
{
    LL x, y;
    LL d=exgcd(a,b,x,y);
    if(c%d!=0)
    {
        return -1;
    }
    x=x*c/d;
    LL t=b/d;
    return (x%t+t)%t;
}
int main()
{
    LL a,b,c,x,y;
    while(cin>>c,c)
    {
        cin>>x>>a>>y>>b;
        if(x*1.0/a<y*1.0/b)
        {
            swap(x,y),swap(a,b);
            LL l=solve(a,b,c);//当ax+by=1时,带入的常数项为1;
            if(l!=-1&&c>=l*a)
                cout<<(c-l*a)/b<<' '<<l<<endl;
            else
                cout<<"failed"<<endl;
        }
        else
        {
            LL l=solve(a,b,c);//当ax+by=1时,带入的常数项为1;
            if(l!=-1&&c>=l*a)
                cout<<l<<' '<<(c-l*a)/b<<endl;
            else
                cout<<"failed"<<endl;
        }
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值