当前位置 : 主页 > 手机开发 > ROM >

Pairs of Numbers

来源:互联网 收集:自由互联 发布时间:2021-06-10
#includestdio.h // we have defined the necessary header files here for this problem. // If additional header files are needed in your program, please import here. /* *函数int deal(int n,int m):处理达到(n,m)转化为(1,1)时需要的次
#include<stdio.h>

//we have defined the necessary header files here for this problem.
//If additional header files are needed in your program, please import here.

/* *

函数int deal(int n,int m):处理达到(n,m)转化为(1,1)时需要的次数
首先保证n<=m
当n==1时,deal(1,m)应该返回 m-1 (规律)
当n不为1且n==m时、或当n < 1时,无法转化到(1,1) 返回无效值-1
将deal(n,m)转化为deal(n,m%n),这里在n远远小于m时,远远比用减号要快,也不会Stackoverflow
如果deal(n,m%n)返回有效值,就把m/n这个转化次数加上返回
函数 resolve(n):对n进行从(1,n-1)(2,n-2)…(n/2,n-n/2)进行遍历调用
如果返回了合法值,就和min比较替换
返回时注意要加上首次拆开时的1次

*/

int deal(int n,int m);
int resolve(int n);

int main(){
  int n;
  while(scanf("%d",&n)!=EOF){
      if(n==1){
          printf("%d\n",0);
      }else{
          printf("%d\n",resolve(n));
      }
      
  }
  return 0;
}

int deal(int n,int m){
    int t = 0;
    if(n>m){
        t=m;
        m=n;
        n=t;
    }

    if(n==1){
        return m-1;
    }

    if((n==m && n!=1) || n<1){
        return -1;
    }

    int changeTimes = m/n;
    int d = deal(n,m%n);
    if(d!=-1){
        return changeTimes+d;
    }

    return -1;
}

int resolve(int n){
    int min = 1000000;
    if(n<=0){
        return 0;
    }
   
    for (int i = 1; i <= n/2; i++)
    {
        int temp = -1;
        temp = deal(i,n-i);
        if( (temp>=0) && (temp<min) ){
            min = temp;
        }
    }
    return min+1;
}

 

题目描述

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.

解答要求时间限制:1000ms, 内存限制:64MB 输入

The input contains the only integer n (1 ≤ n ≤ 106).Process to the end of file.

输出

Print the only integer k.

分享图片

网友评论