UVaLive 6482 A+B

137 篇文章 0 订阅

There is a computer, which has two memory cells (let us denote these
cells by the letters a and b ). Each cell (variable) stores some
integer at any time. The computer can execute only two instructions
a+=b and b+=a . The rst instruction increases the value of the
variable a by the value stored in the variable b . The second one,
respectively, increases the value of b by the value a . A program for
this computer consists of a sequence (possible empty) of such
instructions. The instructions are executed in the appropriate order.
Your task is to determine whether the given value S can be obtained in
some cell after executing some program. Input The input le contains
several test cases, each of them as described below. The input
contains three integers: the initial value of the variable a , the
initial value of the variable b and the required value S (0 a;b;S
10 18 ). SampleOutput For each test case, write to the output YES '
if the required value can be obtained as a result of some program
execution, or
NO ’ otherwise on a line by itself.

可以发现,对于两个系数的来回相加其实就是逆过来的辗转相减。因为初始情况(1,1)的gcd是1,所以来回相加之后只需要保证系数互质。
可以先用扩展欧几里得求出一组x,y使得ax+by=s,然后推出所有非负整数解进行验证。

#include<cstdio>
#include<cstring>
#define LL long long
LL gcd(LL a,LL b,LL &x,LL &y)
{
    if (!b)
    {
        x=1;
        y=0;
        return a;
    }
    LL ret=gcd(b,a%b,y,x);
    y-=a/b*x;
    return ret;
}
int main()
{
    LL a,b,s,d,x,y,t1,t2,A,B;
    bool flag;
    while (scanf("%lld%lld%lld",&a,&b,&s)==3)
    {
        if (a==0&&b==0)
        {
            if (s==0) printf("YES\n");
            else printf("NO\n");
            continue;
        }
        if (a==0)
        {
            if (s%b==0) printf("YES\n");
            else printf("NO\n");
            continue;
        }
        if (b==0)
        {
            if (s%a==0) printf("YES\n");
            else printf("NO\n");
            continue;
        }
        d=gcd(a,b,x,y);
        if (s%d)
        {
            printf("NO\n");
            continue;
        }
        A=a/d;
        B=b/d;
        x=(x%B)*(s/d%B)%B;
        x=(x%B+B)%B;
        y=(s-a*x)/b;
        flag=0;
        while (y>=0)
        {
            if (gcd(x,y,t1,t2)==1)
            {
                flag=1;
                break;
            }
            x+=B;
            y-=A;
        }
        if (flag) printf("YES\n");
        else printf("NO\n");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值