Codeforces Beta Round 7 C. Line 题解 数论 扩展欧几里得

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} 51018 to 5 ⋅ 1 0 18 5·10^{18} 51018 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} 2109<=A,B,C<=2109 ) — 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);
    // 不符合裴蜀定理,无整数解,返回-1
    if (c % d)
        return -1;
    else
    {
        // 有整数解,返回1
        x = 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;
    else
        cout << x << ' ' << y;

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值