Codeforces 134B. Pairs of Numbers (辗转相除)

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 (1n106).

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;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值