• 【算法】广度优先搜索与深度优先搜索 埃及分数


    给定一个分数,如7/8,我们可以把它表示为1/2 + 1/3 +1/24,埃及分数问题即把一个真分数表示为最少的埃及分数之和的形式。

    思路1:

    https://www.jianshu.com/p/da04c77e11d0

    思路2:

    https://wenku.baidu.com/view/7d547518227916888486d78b.html

    NOIP题库:

    http://www.rqnoj.cn/problem

    ACM题库,LEETCODE题库,Lintcode题库。

    这里使用最简单的贪心算法:

    #include <stdio.h>
    
    int gcd(int a, int b);
    
    void reduce(int *a, int *b);
    
    void egypt(int a, int b);
    
    int main(void)
    {
        int a, b;
        scanf("%d/%d", &a, &b);
        egypt(a, b);
        return 0;
    }
    
    int gcd(int a, int b)
    {
        int r;
        if(a < b)
        {
            r = a;
            a = b;
            b = r;
        }
    
        do
        {
            r = a % b;
            a = b;
            b = r;
        }while(b);
        return a;
    }
    
    void reduce(int *a, int *b)
    {
        int common = gcd(*a, *b);
        *a = *a / common;
        *b = *b / common;
    }
    
    void egypt(int a, int b)
    {
        int i = 1, k;
        // 加上一个判断真分数 假分数的。
        reduce(&a, &b);
        printf("After dividing %d / %d
    ", a, b);
    
        while(1)
        {
            if(a == 1)
            {
                printf("1/%d.
    Ending
    ", b);
                break;
            }    
            while(a*++i > b) // a/b > 1/i, 可以分解出1/i
            {
                printf("1/%d + ", i);
                a = a * i - b; // 从a/b中减去那个埃及分数
                b = b * i;    // 通分相减 
                reduce(&a, &b);  // 约分
            }
        }
    }
  • 相关阅读:
    ffmpeg mp4 视频输出为 aac 的命令
    git操作远程分支
    Linux (openSUSE 15.3 ) server ssh 可以使用,sftp无法使用
    小小思考题
    Linux 命令介绍
    2021 年 如何使用VMware 安装 ubuntu 7.04 虚拟机, 配置 apt 源
    Linux 下 命令行 使用浏览器
    oracle.cmd
    Sqlcmd
    vue eslint 配置使用
  • 原文地址:https://www.cnblogs.com/paprikatree/p/10525725.html
Copyright © 2020-2023  润新知