双六(扩展欧几里得算法)

/*
题目描述 :
一个双六上面有向前 向后无限延续的格子, 每个格子都写有整数。其中0号格子是起点,1号格子
是终点。而骰子上只有a,b,-a,-b四个整数,所以根据a和b的值的不同,有可能无法到达终点
掷出四个整数各多少次可以到达终点呢?如果解不唯一,输出任意一组即可。如果无解 输出-1

*/

笔者字不好看。。。。。

                   

下面是代码实现(注意思想)

#include<iostream>
#include<algorithm>
using namespace std;
int extgcd(int a, int b, int& x, int& y)
{
    int d = a;
    if(b != 0)
    {
        d = extgcd(b,a%b,y,x);
        y-=(a/b)*x;
    }
    else
    {
        x=1;y=0;
    }
    return d;
}

int main()
{
    int a, b, x, y;
    int cnt[4] = {0};
    scanf("%d%d", &a, &b);
    if (extgcd(a, b, x, y) != 1)
    {
        cout << -1 << endl;
        return 0;
    }
    if (x > 0) cnt[0] = x;
    else if (x < 0) cnt[2] = -x;
    if (y > 0) cnt[1] = y;
    else if (y < 0) cnt[3] = -y;
    for (int i = 0; i < 4; i++) cout << cnt[i];
    cout << endl;
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/Yinchen-One/p/8921747.html