51 nod 1247 可能的路径(exgcd)

来源:互联网 发布:mac截屏键 编辑:程序博客网 时间:2024/06/08 00:33

1247 可能的路径
题目来源: HackerRank
基准时间限制:1 秒 空间限制:131072 KB 分值: 20 难度:3级算法题
 收藏
 关注
在一个无限大的二维网格上,你站在(a,b)点上,下一步你可以移动到(a + b, b), (a, a + b), (a - b, b), 或者 (a, a - b)这4个点。
给出起点坐标(a,b),以及终点坐标(x,y),问你能否从起点移动到终点。如果可以,输出"Yes",否则输出"No"。
例如:(1,1) 到 (2,3),(1,1) -> (2,1) -> (2,3)。
Input
第1行:一个数T,表示输入的测试数量(1 <= T <= 5000)第2 - T + 1行:每行4个数,a, b, x, y,中间用空格分隔(1 <= a, b, x, y <= 10^18)
Output
输出共T行,每行对应1个结果,如果可以,输出"Yes",否则输出"No"。
Input示例
21 1 2 32 1 2 3
Output示例
YesYes


解:这题直接判断能不能到达 不好考虑 用一个中间桥梁来辅助中间过程 

因为只涉及到 a,b的加减 所以 xa+yb=gcd(a,b)一定有解 如果起点终点能互相到达 那么一定都能到达这个点

#include <algorithm>#include <string.h>#include <iostream>#include <stdio.h>#include <string>#include <vector>#include <queue>#include <map>#include <set>using namespace std;typedef long long LL;const int N = 1e5+10;LL e_gcd(LL a,LL b, LL &x,LL &y){    if(b==0)    {        x=1,y=0;        return a;    }    LL ans=e_gcd(b,a%b,x,y);    LL tmp = x;    x=y;    y=tmp - a/b*y;    return ans;}LL ex(LL a,LL b, LL c, LL &x,LL &y){    LL g = e_gcd(a,b,x,y);    if(c%g)        return -1;    LL mod = b/g;    x*=(c/g);    if(mod<0)        mod=-mod;    x=(x%mod+mod)%mod;    return x;}int main(){    int t;    scanf("%d", &t);    while(t--)    {        LL a, b, c, d;        scanf("%lld %lld %lld %lld", &a, &b, &c, &d);        LL c1=__gcd(a,b),c2=__gcd(c,d);        if(c1==c2) puts("Yes");        else puts("No");    }    return 0;}