【Java版oj】day36Rational Arithmetic、Pre-Post

news2024/9/27 19:21:13

目录

 一、Rational Arithmetic

(1)原题再现

(2)问题分析

(3)完整代码

 二、Pre-Post

(1)原题再现

(2)问题分析

(3)完整代码


 一、Rational Arithmetic

(1)原题再现

Rational Arithmetic (20)__牛客网
 

For two rational numbers, your task is to implement the basic arithmetics, that is, to calculate their sum, difference,
product and quotient.

 

输入描述:

Each input file contains one test case, which gives in one line the two rational numbers in the format "a1/b1 a2/b2". 
The numerators and the denominators are all in the range of long int. If there is a negative sign, it must appear only in 
front of the numerator. The denominators are guaranteed to be non-zero numbers.

输出描述:

For each test case, print in 4 lines the sum, difference, product and quotient of the two rational numbers, respectively. The format of each 
line is "number1 operator number2 = result". Notice that all the rational numbers must be in their simplest form "k a/b", where k is 
the integer part, and a/b is the simplest fraction part. If the number is negative, it must be included in a pair of parentheses. If the 
denominator in the division is zero, output "Inf" as the result. It is guaranteed that all the output integers are in the range of long int.
输入
5/3 0/6
输出
1 2/3 + 0 = 1 2/3<br/>1 2/3 - 0 = 1 2/3<br/>1 2/3 * 0 = 0<br/>1 2/3 / 0 = Inf

(2)问题分析

         

对于两个有理数,你的任务是实现基本的算法,即计算它们的和、差,

乘积和商。

输入描述:

每个输入文件包含一个测试用例,在一行中给出两个有理数,格式为“a1/b1 a2/b2”。分子和分母都在长int的范围内。如果有负号,它必须只出现在分子前面。分母保证为非零数字。


输出描述:

对于每个测试用例,在4行中分别打印两个有理数的和、差、乘积和商。每个的格式第行是“number1运算符number2=结果”。注意,所有有理数都必须是最简单的形式“k a/b”,其中k是整数部分,而a/b是最简单的分数部分。如果数字是负数,则必须将其包含在一对圆括号中。如果除法中的分母为零,输出“Inf”作为结果。可以保证所有输出整数都在长整型的范围内。

(3)完整代码

import java.util.Scanner;

/*
 * 理性算数RationalArithmetic
 */

public class RationalArithmetic {
    public static void simplify(long a, long b) {
        long x = gcd(a, b);
        a /= x;
        b /= x;
        if (b < 0) {
            a *= -1;
            b *= -1;
        }
        if (a < 0) {
            if (-a % b == 0) {
                System.out.print("(" + a / b + ")");
            } else if (-a < b) {
                System.out.print("("+a + "/" + b+")");
            } else {
                System.out.print("(" + a / b + " " + (-a + (b * (a / b))) + "/" + b + ")");
            }
        } else {
            if (a % b == 0) {
                System.out.print(a / b);
            } else if (a < b) {
                System.out.print(a + "/" + b);
            } else {
                System.out.print(a / b + " " + (a - (b * (a / b))) + "/" + b );
            }
        }
    }
    public static long  gcd(long a, long b) { //辗转相除法求最大公约数
        if (b == 0) {
            return a;
        }
        long r = a % b;
        return gcd(b, r);
    }
    public static void add(long a, long b, long c, long d) {
        simplify(a, b);
        System.out.print(" + ");
        simplify(c, d);
        System.out.print(" = ");
        simplify(a * d + b * c, b * d);
    }
    public static void minus(long a, long b, long c, long d) {
        simplify(a, b);
        System.out.print(" - ");
        simplify(c, d);
        System.out.print(" = ");
        simplify(a * d - b * c, b * d);
    }
    public static void multiply(long a, long b, long c, long d) {
        simplify(a, b);
        System.out.print(" * ");
        simplify(c, d);
        System.out.print(" = ");
        simplify(a * c, b * d);
    }
    public static void division(long a, long b, long c, long d) {
        long m = a * d;
        long n = b * c;
        simplify(a, b);
        System.out.print(" / ");
        simplify(c, d);
        System.out.print(" = ");
        if (c == 0) {
            System.out.print("Inf");
        } else {
            if (n < 0) {
                m = m * -1; //把负号调整到分子上
                n = n * -1;
            }
            simplify(m, n);
        }
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String s = sc.nextLine();
            String[] split = s.split(" ");
            String[] s1 = split[0].split("/");
            String[] s2 = split[1].split("/");
            long a = Long.parseLong(s1[0]);
            long b = Long.parseLong(s1[1]);
            long c = Long.parseLong(s2[0]);
            long d = Long.parseLong(s2[1]);
            add(a, b, c, d);
            System.out.println();
            minus(a, b, c, d);
            System.out.println();
            multiply(a, b, c, d);
            System.out.println();
            division(a, b, c, d);
        }
    }
}

 

 二、Pre-Post

(1)原题再现

Pre-Post__牛客网
We are all familiar with pre-order, in-order and post-order traversals of binary trees. A common problem in data structure classes is to find the pre-order traversal of a binary tree when given the in-order and post-order traversals. Alternatively, you can find the post-order traversal when given the in-order and pre-order. However, in general you cannot determine the in-order traversal of a tree when given its pre-order and post-order traversals. Consider the four binary trees below:

All of these trees have the same pre-order and post-order traversals. This phenomenon is not restricted to binary trees, but holds for general m-ary trees as well.

输入描述:

Input will consist of multiple problem instances. Each instance will consist of a line of the form m s1 s2, indicating that the trees are m-ary trees, s1 is the pre-order traversal and s2 is the post-order traversal.All traversal strings will consist of lowercase alphabetic characters. For all input instances, 1 <= m <= 20 and the length of s1 and s2 will be between 1 and 26 inclusive. If the length of s1 is k (which is the same as the length of s2, of course), the first k letters of the alphabet will be used in the strings. An input line of 0 will terminate the input.

输出描述:

For each problem instance, you should output one line containing the number of possible trees which would result in the pre-order and post-order traversals for the instance. All output values will be within the range of a 32-bit signed integer. For each problem instance, you are guaranteed that there is at least one tree with the given pre-order and post-order traversals.
示例1
输入
2 abc cba
2 abc bca
10 abc bca
13 abejkcfghid jkebfghicda
输出
4
1
45
207352860

(2)问题分析

我们都熟悉二叉树的前序、中序和后序遍历。数据结构类中的一个常见问题是,当给定二叉树的中序遍历和后序遍历时,如何找到二叉树的前序遍历。或者,您可以在给定内序和前序时找到后序遍历。然而,当给定树的前序遍历和后序遍历时,通常无法确定树的序遍历。考虑下面的四棵二叉树:

所有这些树都有相同的前序和后序遍历。这种现象并不局限于二叉树,也适用于一般的m-ary树。

输入描述:
输入将由多个问题实例组成。每个实例将由m s1 s2形式的一行组成,表示树是m-ary树,s1是前序遍历,s2是后序遍历。所有遍历字符串将由小写字母字符组成。对于所有输入实例,1 <= m <= 20, s1和s2的长度将介于1到26之间。如果s1的长度是k(当然与s2的长度相同),字母表的前k个字母将被用于字符串中。输入行为0将终止输入。
输出描述:
对于每个问题实例,您应该输出一行,其中包含可能的树的数量,这将导致实例的前序和后序遍历。所有输出值都将在32位有符号整数的范围内。对于每个问题实例,保证至少有一棵树具有给定的前序和后序遍历。

(3)完整代码

/*
 * 前柱Pre-Post
 */
import java.util.*;
class SubTree {
    public SubTree(String pre, String post) {
        this.pre = pre;
        this.post = post;
    }
    String pre;
    String post;
}
public class Main {
    //计算阶乘
    public static  long fac(int n) {
        long f = 1;
        for (int i = 1; i <= n; i++) {
            f *= i;
        }
        return f;
    }
    //计算C n m
    public static long calcCom(int n, int m) {
        m = m < (n - m) ? m : (n - m);
        long r = 1;
        for (int i = n; i >= n - m + 1; i--) {
            r *= i;
        }
        return r / fac(m);
    }
    public static List<SubTree> calcSubTree(String prev, String post) {
        //子树的根在前序遍历结果中的位置
        int subRootPreIdx = 1;
        //后序遍历
        int postFirst = 0;
        List<SubTree> subTreeList = new ArrayList<>();
        while (subRootPreIdx < prev.length()) {
            //确认该棵子树的根节点
            char rootSub = prev.charAt(subRootPreIdx);
            int subRootPostIdx = post.indexOf(rootSub);
            int subTreeNodeCount = subRootPostIdx - postFirst + 1;
            //从前序和后续遍历结果中分离出该棵子树的前序和后序遍历结果
            SubTree subTree = new SubTree(
                prev.substring(subRootPreIdx, subRootPreIdx + subTreeNodeCount),
                post.substring(postFirst, postFirst + subTreeNodeCount)
            );
            subTreeList.add(subTree);
            //继续分离下一棵子树
            subRootPreIdx += subTreeNodeCount;
            postFirst += subTreeNodeCount;
        }
        return subTreeList;
    }
    public static long CalcTreePossible(int m, String pre, String post) {
        if (pre.isEmpty() || pre.length() == 1) {
            return 1;
        }
        //先分离出根节点有多少棵树
        List<SubTree> subTree =  calcSubTree(pre, post);
        //根节点子树可能性的组合结果
        long result = calcCom(m, subTree.size());
        //根的子树有多少种可能性
        for (SubTree e : subTree) {
            result *= CalcTreePossible(m, e.pre, e.post);
        }
        return result;
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int m = in.nextInt();
            if (m == 0) {
                break;
            }
            //接收子树的前序和后续遍历结果
            String pre = in.next();
            String post = in.next();

            System.out.println(CalcTreePossible(m, pre, post));
        }
    }
}

 


 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/430108.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

十七、小程序报错 真机调试预览失效 Error: Illegal Buffer

报错 电脑端微信开发者工具运行成功而真机调试预览失效 报错 MiniProgramError Illegal Buffer 报错 {errno: 600001, errMsg: “request:fail -200:net::ERR_CERT_COMMON_NAME_INVALID”} 前言&#xff1a;手头有个去年的微信小程序项目 年底甲方不在使用 所以停掉了服务器、…

互联网医院系统构建:探索开源云平台与互联网医院平台源码的融合

互联网医院系统作为一种新型医疗服务模式&#xff0c;将传统的医院门诊转化为在线咨询、远程会诊等形式&#xff0c;帮助患者更加方便地获得专业医疗服务。 在实现互联网医院系统的建设过程中&#xff0c;选择合适的云平台和医院平台源码是至关重要的。 首先&#xff0c;开源…

LVM逻辑卷管理

目录一、LVM简介1、逻辑卷管理磁盘的优点2、缺陷3、LVM概述图二、LVM的使用1、创建逻辑卷2、使用逻辑卷3、删除逻辑卷4、LVM扩容5、LVM缩容三、Snapshot&#xff08;快照功能&#xff09;1、LVM-snapshot简介2、利用snapshot做备份&#xff08;LV快照&#xff09;四、LVM数据迁…

整型在内存中的存储

在计算机底层&#xff0c;所有数据最终都会被表示为二进制形式。整型也不例外。本文将介绍在C语言中如何定义和操作整型变量&#xff0c;并解释整型在内存中的存储方式。 整型变量的定义和使用 在C语言中&#xff0c;可以用int关键字来定义一个整数型变量。例如&#xff1a; …

ChatGPT们接踵而至,AI会彻底改变我们的工作方式吗?

2023年开年&#xff0c;AI成为了舞台上聚光灯下的主角&#xff0c;AI 浪潮不仅让我们对人工智能的能力有了一次全新的理解&#xff0c;而且所有人的工作和生活都将受到不同程度的影响。 ChatGPT、Notion AI、New Bing、GPT-4、MidJourney v5、office copilot、Adobe Firefly、…

解决方案:炼丹师养成计划 Pytorch如何进行断点续训——DFGAN断点续训实操

我们在训练模型的时候经常会出现各种问题导致训练中断&#xff0c;比方说断电、系统中断、内存溢出、断连、硬件故障、地震火灾等之类的导致电脑系统关闭&#xff0c;从而将模型训练中断。 所以在实际运行当中&#xff0c;我们经常需要每100轮epoch或者每50轮epoch要保存训练好…

Python实现哈里斯鹰优化算法(HHO)优化卷积神经网络分类模型(CNN分类算法)项目实战

说明&#xff1a;这是一个机器学习实战项目&#xff08;附带数据代码文档视频讲解&#xff09;&#xff0c;如需数据代码文档视频讲解可以直接到文章最后获取。 1.项目背景 2019年Heidari等人提出哈里斯鹰优化算法(Harris Hawk Optimization, HHO)&#xff0c;该算法有较强的全…

DAY 43 Apache的配置与应用

虚拟Web主机 概述 虚拟web主机指的是在同一台服务器中运行多个web站点&#xff0c;其中每一个站点实际上并不独立占用整个服务器&#xff0c;因此被称为"虚拟"web主机。通过虚拟web主机服务可以充分利用服务器的硬件资源&#xff0c;从而大大降低网站构建及运行成本…

TensorFlow 决策森林详细介绍和使用说明

使用TensorFlow训练、调优、评估、解释和部署基于树的模型的完整教程 两年前TensorFlow (TF)团队开源了一个库来训练基于树的模型&#xff0c;称为TensorFlow决策森林(TFDF)。经过了2年的测试&#xff0c;他们在上个月终于宣布这个包已经准备好发布了&#xff0c;也就是说我们…

在android项目上集成libyuv库以及使用linyuv库完成camera的缩放,旋转,翻转,裁剪操作

目录 一、下拉google官方的libyuv库代码 二、在android项目中集成libyuv库 1.环境配置 2.拷贝libyuv源码文件 ​编辑3.配置cmake libyuv相关的链接编译等 三、使用libyuv库 1.libyuv库完成camera的旋转 2.libyuv库实现翻转 3.libyuv库实现缩放 4.libyuv库实现裁剪 一…

为什么重视安全的公司都在用SSL安全证书?

我们今天来讲一讲为什么重视安全的公司都在用SSL证书 SSL证书是什么&#xff1f; SSL安全证书是由权威认证机构颁发的&#xff0c;是CA机构将公钥和相关信息写入一个文件&#xff0c;CA机构用他们的私钥对我们的公钥和相关信息进行签名后&#xff0c;将签名信息也写入这个文件…

对于数据库而言,其锁范围可以分为全局锁 、表级锁、 行级锁

一、全局锁 全局锁就是对整个数据库实例加锁。 MySQL 提供了一个加全局读锁的方法&#xff0c;命令是 Flush tables with read lock (FTWRL)。当你需要让整个库处于只读状态的时候&#xff0c;可以使用这个命令&#xff0c;之后其他线程的以下语句会被阻塞&#xff1a;数据更新…

DOM(1)

DOM&#xff08;文档对象模型&#xff09;&#xff1a;处理可扩展标记语言(HTML或XML&#xff09;的标准编程接口&#xff0c;可以改变网页的内容、结构和样式。DOM树&#xff1a; …

ubuntu18 网络问题

在/etc/netplan/*.yaml配置文件中&#xff1a; renderer的值可以是networkd&#xff0c;或者是NetworkManager 它俩的其中一个区别为&#xff1a; networkd在图像界面&#xff0c;networking setting中不显示网卡配置。 版权简介&#xff1a; 从Ubuntu 18.04.2版本开始&…

腾讯云4核8G轻量服务器12M支持多少访客同时在线?并发数怎么算?

腾讯云轻量4核8G12M轻量应用服务器支持多少人同时在线&#xff1f;通用型-4核8G-180G-2000G&#xff0c;2000GB月流量&#xff0c;系统盘为180GB SSD盘&#xff0c;12M公网带宽&#xff0c;下载速度峰值为1536KB/s&#xff0c;即1.5M/秒&#xff0c;假设网站内页平均大小为60KB…

网络安全:网络攻击原理与方法.

网络安全&#xff1a;网络攻击原理与方法. 网络攻击&#xff1a;是损害网络系统安全属性的危害行为。危害行为导致网络系统的机密性、完整性、可控性、真实性、抗抵赖性等受到不同程度的破坏。 目录&#xff1a; 常见的危害行为有四个基本类型&#xff1a; 网络攻击模型&…

项目实践 | 行人跟踪与摔倒检测报警

项目实践 | 行人跟踪与摔倒检测报警 小白学视觉 7月7日 原文地址&#xff1a;项目实践 | 行人跟踪与摔倒检测报警 1.简介 本项目的目的是为了给大家提供跟多的实战思路&#xff0c;抛砖引玉为大家提供一个案例&#xff0c;也希望读者可以根据该方法实现更多的思想与想法&…

为什么Uber从PostgreSQL换成了MySQL

说明&#xff1a;本文翻译自Why Uber Engineering Switched from Postgres to MySQL 引言 Uber的早期架构包括一个用Python编写的单一后端应用程序&#xff0c;它使用Postgres进行数据持久化。从那时起&#xff0c;Uber的架构发生了重大变化&#xff0c;转向了微服务和新数据…

比例放大器设置接线US-DAS1/US-DAS2

US-DAS1、US-DAS2比例放大器接线定义 1 CMD 指令 2 CMD- 指令- 3/4/5 N.C. 不接 6 ENA 使能 7 VREF_5V 参考电压5V 8 VREF_0V 参考电压0V 9 SOL_A 电磁铁A 10 SOL_A- 电磁铁A- 11 PWR 电源 12 PWR- 电源- 13 SOL_B- 电磁铁B- 15 RS485_A - 16 RS485_B -

LeetCode-盛最多水的容器-11题

LeetCode-盛最多水的容器-11题 题目中要求计算最大面积&#xff0c;即需要选择对应的长和宽。 最终解决方法&#xff1a;使用对撞指针 对撞指针的概念&#xff1a;是指在数组的两个端引入两个指针&#xff0c;左指针不断向右移动&#xff0c;右指针不断向左移动。最终到达两个…