数字对

题目描述

对于一个数字对(a, b),我们可以通过一次操作将其变为新数字对(a+b, b)或(a, a+b)。

给定一正整数n,问最少需要多少次操作可将数字对(1, 1)变为一个数字对,该数字对至少有一个数字为n。

输入输出格式

输入格式:

第一行一个正整数 n

输出格式:

一个整数表示答案。

输入输出样例

输入样例#1:
5
输出样例#1:
3

说明

样例解释:

(1,1)  →  (1,2)  →  (3,2)  →  (5,2)

对于30%的数据, 1 <= n <= 1000

对于60%的数据, 1 <= n <= 20000

对于100%的数据,1 <= n <= 10^6

题解:

已知数对(x,y),假设x>y,那么只能由(x-y,y)得到

这里有点眼熟,就是更相减损术

那么直接变成辗转相除

枚举i

求出得到(n,i)的步数

复杂度O(nlogn)

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<queue>
 6 using namespace std;
 7 int n,ans=2e9,step;
 8 int main()
 9 {int i,x,y,s;
10   cin>>n;
11   for (i=1;i<=n;i++)
12     {
13       int x=n,y=i;
14       step=0;
15       while (1)
16     {
17       if (x<y) swap(x,y);
18       if (!y) break;
19       if (y==1)
20         {
21          step+=x-1;
22              if (step<ans) ans=step;
23          break;
24         }
25       step+=x/y;
26       x=x%y;
27     }
28     }
29   cout<<ans;
30 }

 

posted @ 2017-08-29 14:10  Z-Y-Y-S  阅读(389)  评论(0编辑  收藏  举报