Line
题目描述
A line on the plane is described by an equation A x + B y + C = 0 Ax+By+C=0 Ax+By+C=0 . You are to find any point on this line, whose coordinates are integer numbers from − 5 ⋅ 1 0 18 -5·10^{18} −5⋅1018 to 5 ⋅ 1 0 18 5·10^{18} 5⋅1018 inclusive, or to find out that such points do not exist.
输入格式
The first line contains three integers A A A , B B B and C C C ( − 2 ⋅ 1 0 9 < = A , B , C < = 2 ⋅ 1 0 9 -2·10^{9}<=A,B,C<=2·10^{9} −2⋅109<=A,B,C<=2⋅109 ) — corresponding coefficients of the line equation. It is guaranteed that A 2 + B 2 > 0 A^{2}+B^{2}>0 A2+B2>0 .
输出格式
If the required point exists, output its coordinates, otherwise output -1.
题面翻译
一条直线:Ax+By+C=0(A,B不同时为0),找到任意一个点(在-5e18~5e18之间),让它的横纵坐标均为整数,或者确定没有这样的点。
样例 #1
样例输入 #1
2 5 3
样例输出 #1
6 -3
原题
Codeforces——传送门
洛谷——传送门
思路
将求 A x + B y + C = 0 Ax+By+C=0 Ax+By+C=0 直线上的整数点转化为求 A x + B y = − C Ax+By=-C Ax+By=−C 的一个整数解。然后利用扩展欧几里得算法求其中一个解即可。
代码
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;i64 a, b, c, x, y;
// exgcd求出ax+by=gcd(a,b)的解
i64 exgcd(i64 a, i64 b, i64 &x, i64 &y)
{if (b == 0){x = 1, y = 0;return a;}i64 d = exgcd(b, a % b, y, x);y -= (a / b * x);return d;
}
// 求解不定方程ax+by=c
int func()
{i64 d = exgcd(a, b, x, y);// 不符合裴蜀定理,无整数解,返回-1if (c % d)return -1;else{// 有整数解,返回1x = x * c / d;y = y * c / d;return 1;}
}int main()
{ios::sync_with_stdio(0);cin.tie(0);cin >> a >> b >> c;c = -c; // c平移后变为-c即ax+by+c=0到ax+by=-c的转化if (func() == -1)cout << -1;elsecout << x << ' ' << y;return 0;
}