Cf 406 A. The Monster

Rick 和 Morty被一只怪物追赶,在不同时间点尖叫。怪物会在他们同时尖叫时抓住他们。给定Rick和Morty尖叫的时间序列,任务是找出它们首次同步尖叫的时刻或者表明他们永远不会同步。输入包含两个尖叫序列的起始时间和增量,输出首次同步的时间或-1表示永不同步。题目要求使用扩展欧几里得算法找到正整数解。
摘要由CSDN通过智能技术生成

A. The Monster
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, ....

The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.

Input

The first line of input contains two integers a and b (1 ≤ a, b ≤ 100).

The second line contains two integers c and d (1 ≤ c, d ≤ 100).

Output

Print the first time Rick and Morty will scream at the same time, or  - 1 if they will never scream at the same time.

Examples
input
20 2
9 19
output
82
input
2 1
16 12
output
-1
Note

In the first sample testcase, Rick's 5th scream and Morty's 8th time are at time 82.

In the second sample testcase, all Rick's screams will be at odd times and Morty's will be at even times, so they will never scream at the same time.

我们可以想到求:ax+b=cy+d;

直接套个扩欧的板子,嗯需要注意的就是,求出x最小正整数解来之后,y的值不一定是正整数,这时候要确保y也是正整数。

由于移项之后变成ax-cy=d-b;也就是ax+c(-y)=d-b;所以我们求出来的y应当大于等于0,那么-y就应当小于0了。当-y大于0的时候我们增加x这样下去自然就可以得到正整数的y了。

#include <bits/stdc++.h>

using namespace std;
const int MAXN=520;
const int inf=1e9;
void exgcd(int a,int b,int &g,int &x,int &y)
{
    if(!b)
    {
        x=1;
        y=0;
        g=a;
    }
    else
    {
        exgcd(b,a%b,g,y,x);
        y-=a/b*x;
    }
}
int main()
{
    int a,c1,b,c2;
    scanf("%d%d%d%d",&a,&c1,&b,&c2);
    int c=c2-c1;
    int g,x,y;
    exgcd(a,b,g,x,y);
    if(c%g)puts("-1");
    else
    {
        int b1=b/g;
        x*=(c/g);
        x=(x%b1+b1)%b1;
        while((c-a*x)/b>0)x+=b1;
        printf("%d\n",a*x+c1);
    }
    return 0;
}

看不懂扩欧的看博客 数论->扩欧



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值