Description
Let’s assume that we have a pair of numbers ( a, b). We can get a new pair ( a + b, b) or ( a, a + b) from the given pair in a single step.
Let the initial pair of numbers be (1,1). Your task is to find number k, that is, the least number of steps needed to transform (1,1) into the pair where at least one number equals n.
Input
The input contains the only integer
n
(
1
≤
n
≤
1
0
6
)
n~(1 ≤ n ≤ 10^6)
n (1 ≤ n ≤ 106).
Output
Print the only integer k.
Examples
Input
5
Output
3
Input
1
Output
0
Note
The pair (1,1) can be transformed into a pair containing 5 in three moves: (1,1) → (1,2) → (3,2) → (5,2).
Solution
先正向考虑,发现从初始状态(1,1)向其他任何状态转移时,形成了一颗二叉树,所以对于任意合法状态,一定有唯一的路径向上到达初始状态。
再注意到,该路径一定是不断将大数加到小数上形成的
因此我们枚举最后的状态(一定是n和小于n),取所有合法状态的最小操作次数即可
Code
int tmp;
void dfs(int a,int b){
if(b == 0) {
//非法状态
tmp = INF;return ;
} else if(b == 1){
//合法最终状态
tmp += a - 1; return ;
}
tmp += a / b; // 上层状态到当前状态的步数
dfs(b,a % b);
}
int main() {
int n;scanf("%d",&n);
int res = n - 1;
for(int i = 1;i < n;++i){
tmp = 0;
dfs(n,i);
res = min(res, tmp);
}
printf("%d\n", res);
return 0;
}