zoukankan      html  css  js  c++  java
  • Pairs of Numbers

    #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
    ",0);
          }else{
              printf("%d
    ",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.

  • 相关阅读:
    将数组转换为 List, 使用 Collections.addAll(arrayList, array)
    Numpy学习笔记
    sql 批量修改字段内容
    sql 查询的优化
    选择低薪喜欢的工作, 还是高薪不喜欢的工作 ?
    Tornado + Bootstrap 快速搭建自己的web应用
    sql查询出现次数最多的记录的名称和现次数以及QT聚合查找失败解决
    idea中修改git提交代码的用户名
    初识Spring Cloud与微服务
    微信小程序解析富文本的几种方法
  • 原文地址:https://www.cnblogs.com/ustc-anmin/p/11265363.html
Copyright © 2011-2022 走看看