传送门:Min Chain
Min Chain
Source : 2009 China North East Local Contest | |||
Time limit : 2 sec | Memory limit : 64 M |
Submitted : 387, Accepted : 103
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.
解题报告:
分析:
扩展的欧几里德算法,ax+by=gcd(a,b),若gcd(a,b)!=1,输出-1,否则,用扩展的欧几里德算法求出
最小的x与y即可,注意到
当存在0时,若有1输出1,否则输出-1;
当存在1,若有2输出1,否则输出2(因为直接a-a+1即可)
当上面都不满足时,直接用扩展的欧几里德算法求出x,在解方程求出y,两绝对值相加减一即可
代码如下:
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
long long ext_gcd(long long a,long long b,long long &x,long long &y){
if(b==0){
x=1;y=0; return a;
}
long long d=ext_gcd(b,a%b,x,y);
long long xt=x;
x=y;
y=xt-a/b*y;
return d;
}
int main(){
int t;
scanf("%d",&t);
while(t--){
long long a,b,c=1;
scanf("%lld%lld",&a,&b);
if(b>a)
swap(a,b);
if(b==0){
if(a==1)
printf("1\n");
else
printf("-1\n");
}
else if(a==2&&b==1)
printf("1\n");
else if(b==1)
printf("2\n");
else{
long long x,y;
long long d=ext_gcd(a,b,x,y);
if(d!=1)
printf("-1\n");
else{
int e;
e=x*c/b;
x=c*x-e*b;
y=(1-a*x)/b;
long long ans=abs(x)+abs(y);
printf("%lld\n",ans-1);
}
}
}
return 0;
}