Min Chain
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; }