您的位置:首页 > 其它

POJ - 1061 青蛙的约会(扩展欧几里得)

2017-08-25 22:03 363 查看
题目链接:http://poj.org/problem?id=1061

中文题0.0

思路:扩展欧几里得算法的模板题,通过把等式变形得到a=m-n,b=l,c=y-x,然后如果c%gcd不等于0的话,那显然是不行的,如果等于0,那么a,b,c都同除以gcd,然后x,y还要同除以c/gcd,这时才满足ax`+by`=1的模式,此时x`=x/(c/gcd),那么x=x`*(c/gcd),再保证都是正数就行了。

代码:

#include <cstdio>

#include <cmath>

#include <iostream>

#include <cstring>

#include <algorithm>

#include <queue>

#include <stack>

#include <vector>

#include <map>

#include <numeric>

#include <set>

#include <string>

#include <cctype>

#include <sstream>

#define INF 0x3f3f3f3f

using namespace std;

typedef long long LL;

typedef pair<int, int> P;

const int maxn = 5e5 + 5;

LL extgcd(LL a,LL b,LL &t,LL &k){

    LL d=a;

    if (b!=0){

        d=extgcd(b,a%b,k,t);

        k-=(a/b)*t;

    }

    else {

        t=1;k=0;

    }

    return d;

}

int main () {

    //freopen ("in.txt", "r", stdin);

    LL x,y,m,n,l,t,k;

    cin>>x>>y>>m>>n>>l;

    LL a=m-n,b=l,c=y-x;

    LL g=extgcd(a,b,t,k);

    if (c%g) cout<<"Impossible"<<endl;

    else {

        b/=g;

        c/=g;

        t=t*c;

        if (b<0) b=-b;

        t%=b;

        if (t<=0) t+=b;

        cout<<t<<endl;

    }

    return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: