codeforce 787 A. The Monster
来源:互联网 发布:淘宝店铺解封软件 编辑:程序博客网 时间:2024/05/22 15:22
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.
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).
Print the first time Rick and Morty will scream at the same time, or - 1 if they will never scream at the same time.
20 29 19
82
2 116 12
-1
这个题目使我对于扩展欧几里得的理解更深了。
b+x*a=d+y*c -->a*x-c*y=d-b 因为适用条件是a、c为不完全为零的非负整数。
所以这个题目潜在的要求是:在多组解中选出x>0,y<0的情况。
具体细节详见代码注释;
#include<stdio.h>int ans;int Exgcd(int a,int b,int &x,int &y){if(b==0){x=1; y=0;return a;}int gg=Exgcd(b,a%b,y,x);y-=a/b*x;return gg;}int cal(int a,int b,int c,int d){int x,y;int gg=Exgcd(a,c,x,y);if((d-b)%gg!=0)return 0;else{int m=c/gg;printf("xy = %d%d",x,y);x=(d-b)/gg*x;//先按照gg与d-b倍数关系转化 y=(d-b)/gg*y;x=((x%m)+m)%m;//将x转化为最小正整数 y=(d-b-a*x)/c;while(y>0)//在y大于0的时候不断增大x。 {x+=m;//在通解中找出特解。 y=(d-b-a*x)/c;}ans=b+a*x;}return 1;}int main(){int a,b,c,d;while(~scanf("%d%d%d%d",&a,&b,&c,&d)){if(cal(a,b,c,d))printf("%d\n",ans);elseprintf("-1\n");}return 0;}
- codeforce 787 A. The Monster
- codeforce 787A The Monster 两种解法
- CodeForces 787A The Monster
- CodeFroces 787A The Monster
- The Monster (Codefores-787A)
- A. The Monster
- CodeForces 787A A. The Monster(扩展欧几里得)
- Cf 406 A. The Monster
- codeforces 787A The Monster (猜想 + 证明)
- codeforces 787A The Monster 扩展欧几里德 Java
- codeforces 487A Fight the Monster
- 【Codeforces】 487A Fight the Monster
- CodeForces 487A Fight the Monster
- codeforces #487A# Fight the Monster(枚举)
- Codeforces 487A Fight the Monster(暴力)
- Codeforces 487A Fight the Monster
- A - Kill the monster (DFS)
- The Monster
- 基础邮件原理(MUA,MTA,MDA)
- 排队
- MySQL入门--显示表结构的两种方式
- Android布局
- 无剑无我 (水题)精度问题
- codeforce 787 A. The Monster
- Linux中最受欢迎的邮件传输代理(MTA)
- 如何使用Blender将点模型的obj文件渲染成网格模型
- manacher算法入门HDU5731
- sublime text3怎样快速成为html格式
- 如何防暴力破解??
- 运算符重载
- C++学习:拷贝构造函数
- 解析xml