Daily Practice-Q2-Dr. Bei’s Mechanical Parts-20231001

Table of contents

1.Title description

2. Enter a description

3. Sample tips

4.Problem analysis

5. Via code


1.Title description

  Dr. Bay is a busy man. He is designing and building a very complex mechanical computer. Dr. Bei is a little worried recently because there are many types of mechanical parts and they wear out quickly, so the funds are not enough. However, he discovered that after some mechanical parts wear out, several worn parts of the same model can be remelted and then cast into a new part of the same model. Mechanical parts that meet this characteristic are called refurbished parts. So Dr. Bei invited his assistant, Miss Ai, and asked her to count how many types of refurbished parts there are, how many of each type are currently in stock, and how many old parts can be recast to cast a new part. He asked her to calculate the corresponding The final number of parts he can use for each mechanical part.

2. Enter a description

  The first line inputs two numbers p and q, which means that the stock of parts of a certain model is p, and q old parts can be re-cast to cast a new part.

3. Sample tips

Output: The final number of units of each refurbished mechanical part that can be used.

4.Problem analysis

这道题比较复杂而且误导性很强,以下我将逐层分析这道题,我也花了很久的时间,可能是有段时间没有做OJ题了。
题目分析:本题是要求我们求出所有的被用到的零件个数,但是测试样例6 6其实就一个过程就结束了,让做题的人
简单以为只要简单一个循环就行,实际上不然,本题的循环跳出条件需要实时分析。
由于测试样例6 6太过简单,我们另外举例两个数来讲解(30,4).
一共四个参数p,q,r,sum,r是表示废品区的废品数量。
循环分析如下所示:
首先初始值为的值为输入的值。
第一轮循环分为两步:1.30个产品全部用完,移入废品区,同时sum计数开始。
                  2.废品区开始重铸30/4=7,剩下2个,7个产品移入产品区(p),sum此时不计数
第一轮数据结果分为两行如下表所示。

第二轮循环分为两步:1.7个产品全部用完,移入废品区,同时sum计数开始。
                  2.废品区开始重铸7/4=2,剩下1个,2个新产品移入产品区(p),sum此时不计数
第二轮数据结果分为两行如下表所示。

第三轮循环分为两步:1.2个产品全部用完,移入废品区,同时sum计数开始。
                  2.废品区开始重铸2/4=0,剩下3个,此时的r<q,不会在产生新产品了,循环结束
第三轮数据结果分为两行如下表所示。


产品循环各区数据表
         p      q      r     sum
 begin   30     4      0     0
 First_1 0      4      30    30
 First_2 7      4      2     30
 Secon_1 0      4      9     37
 Secon_2 2      4      1     37
 Third_1 0      4      3     39(r<q,out!)

5. Via code

#include<iostream>
using namespace std;
int main()
{
  int p,q;
  int r=0;
  int sum=0;
  cin>>p>>q;
  while(true)
  {
      //循环第一步
      sum+=p;
      r=r+p;
      p=0;
      
      //判定条件
      if(r<q) break;
      
      //循环第二步
      p=r/q;
      r=r%q;
  }
  cout<<sum<<endl;
  return 0;
}

Guess you like

Origin blog.csdn.net/m0_71819746/article/details/133464846