H.I.T_2815---扩展欧几里德

本文探讨了如何通过加减操作使两个整数得到1的最少步骤问题,并提供了使用扩展欧几里德算法的实现代码。针对不同输入,算法能够找到达到目标所需的最短路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Min Chain

My Tags  (Edit)
 Source : 2009 China North East Local Contest
 Time limit : 2 sec Memory limit : 64 M

Submitted : 435, Accepted : 117

Problem Description

Raven likes games of numbers. Today he meets two numbers and thinks whether he could get a result of 1 by doing at least one operation (addition or subtraction). However, he is tired of calculation; he also wants to know the minimum steps of operation that he could get 1.

Input Details

The first line of the input contains an integer T, which indicates the number of test cases.

In the following T rows, there are two positive integers a, b ( 0<=a, b<=10^9) in each row.

Output Details

For each case, output the least number of steps.

If you cannot get 1, just output -1.

Sample Input

3
3 2
16 9
6 8

Sample Output

1
10
-1

Hint

Sample 1: 3 - 2 = 1, One subtraction will be needed.
Sample 2: 16-9+16-9+16-9-9-9+16-9-9=1,It requires 10 additions and subtractions.
Sample 3: You cannot get 1.
此题还是看学长博客才发现自己漏掉好多情况,而且对扩展欧几里德算法没有真正搞明白,自己太没有钻研精神啊--。
#include <iostream>
#include <math.h>
using namespace std;
void ex(long long a,long long b,long long &x,long long &y)
{
    if(b==0)
    {
        x=1;
        y=0;
       return;
    }
    ex(b,a%b,x,y);
    long long tmp=x;
    x=y;
    y=tmp-(a/b)*y;
}
long long gcd(long long a,long long b)
{
    if(b==0)
    return a;
    return gcd(b,a%b);
}
int main()
{
    long long a,b,x,y;
    long long ans;
    int t;
    cin>>t;
    while(t--)
    {  cin>>a>>b;
    if(a<b)
    swap(a,b);
       if(gcd(a,b)!=1)
       {cout<<"-1"<<endl;
       continue;
       }
          if(b==1&&a==2)
            {
              cout<<"1"<<endl;
              continue;
            }
            if(b==1)
            {
               cout<<"2"<<endl;
               continue;
            }
            if(b==0&&a==1)
            {
                cout<<"1"<<endl;
                continue;
            }
           ex(a,b,x,y);
           ans=fabs(x)+fabs(y);
           if(x<0)
           {
               long long tmp=fabs(x+b)+fabs(y-a);
               if(tmp<ans)
               ans=tmp;
           }
           else
           {
               long long tmp=fabs(x-b)+fabs(y+a);
               if(tmp<ans)
               ans=tmp;
           }
           cout<<ans-1<<endl;

    }
    //cout << "Hello world!" << endl;
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值