题目链接:点击打开链接
http://codeforces.com/contest/7/problem/C
C. Line
扩展GCD。
// 扩展欧几里德算法,解gcd(a, b) = ax + by
// 结果存储在x,y中,用户调用时保证a、b、c都是整数
// 返回a,b的最大公约数
ll exgcd(ll a,ll b,ll &x,ll &y)
{
if(!a && !b)return -1;
if(!b)return x=1,y=0,a;
ll d=exgcd(b,a%b,y,x);
return y-=a/b*x,d;
}
// 等式ax+by=c,已知a、b、c,求x和y。
// 解该线性方程等同于解同余式ax = c(mod b)
// 返回值表示是否有解,true有解,false无解
bool linear_equation(int a, int b, int c, int &x, int &y)
{
int n = exgcd(a, b, x, y);
if(c%n)
return false;
int k = c/n;
x *= k;
y *= k;
return true;
}
AC代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll exgcd(ll a,ll b,ll &x,ll &y)
{
if(!a && !b)return -1;
if(!b)return x=1,y=0,a;
ll d=exgcd(b,a%b,y,x);
return y-=a/b*x,d;
}
int main()
{
ll a,b,c,x,y,t;
scanf("%lld%lld%lld",&a,&b,&c);
t=exgcd(a,b,x,y);
// cout<<t<<endl;
//cout<<x<<endl;
// cout<<y<<endl;
if(c%t) return 0*printf("-1");
x *= -c/t;
y *= -c/t;
return 0*printf("%lld %lld",x,y);
}