2661: 数字游戏
Result | TIME Limit | MEMORY Limit | Run Times | AC Times | JUDGE |
---|---|---|---|---|---|
2s | 32768K | 357 | 40 | Standard |
Raven很喜欢数字游戏,今天他看到两个数,就想能否通过简单的加减,使最终答案等于1。而他又比较厌烦计算,所以他还想知道最少经过多少步加减才能得到1。好吧,我想,是你开动脑筋的时候了。 (注意:至少需要做一步加减法)
Input
输入包含多组数据。第一行有一个正整数T,表明输入数据的组数。接下来T行,每行有2个非负整数a,b (0 <= a,b <= 1000000000)
Output
输出最少的步数。如果无法得到1,则输出-1.
Input
3 3 2 16 9 6 8
Output
1 10 -1
Hint
Sample 0: 3 - 2 = 1,需要做1次减法 Sample 1: 16-9+16-9+16-9-9-9+16-9-9=1,需要做10次加减法. Sample 2: 不能得到1
Problem Source: necpc
#include<stdio.h>
const int d=1;
int abs(int x) {return x>0?x:-x;}
int exgcd(int a, int b,int &x0,int &y0)
{
int r;
if (!b)
{
r = a;
x0= 1;
y0= 0;
return r;
}
r = exgcd(b, a % b,x0,y0);
int t = x0;
x0 = y0;
y0 = t-a/b*y0;
return r;
}
int main()
{
int a,b,x0,y0,k,T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&a,&b);
//a*x0+b*y0=d,d=1;
int r=exgcd(a,b,x0,y0);
if(r!=1) {printf("%d/n",-1);continue;}
if(a==1||b==1)
{
if(a+b==1||a+b==3) printf("1/n");
else printf("2/n");
continue;
}
int t=abs(x0)+abs(y0);
printf("%d/n",t-1);
/*k=-x0/b;
x0=x0+k*b;
if(x0<0) x0+=b;
printf("%d/n",x0);*/
}
return 0;
}