📜  使用N根管填充水箱所需的最短时间

📅  最后修改于: 2021-04-28 17:56:43             🧑  作者: Mango

给定总共N + 1条管道所需的时间,其中N条管道用于填充水箱,而一条管道用于清空水箱。任务是计算如果同时打开所有N + 1个管道,水箱将被充满的时间。

例子

Input: n = 2, 
pipe1 = 12 hours, pipe2 = 14 hours,
emptypipe = 30 hours
Output: 8 hours

Input: n = 1, 
pipe1 = 12 hours
emptypipe = 18 hours
Output: 36 hours 

方法:

  • 如果pipe1可以在’n’小时内填充一个水箱,则在1小时内,pipe1将能够填充’1 / n’水箱。
  • 同样,如果pipe2可以在’m’小时内填充一个水箱,那么在一小时内,pipe2将能够填充’1 / m’水箱。
  • 很快…。用于其他管道。

因此,在1小时内用N条管道填充储水池的总工作量为

考虑两个管道的示例:

下面是上述方法的实现:

C++
// C++ implementation of above approach
#include 
using namespace std;
 
// Function to calculate the time
float Time(float arr[], int n, int Emptypipe)
{
 
    float fill = 0;
    for (int i = 0; i < n; i++)
        fill += 1 / arr[i];
 
    fill = fill - (1 / (float)Emptypipe);
 
    return 1 / fill;
}
 
// Driver Code
int main()
{
    float arr[] = { 12, 14 };
    float Emptypipe = 30;
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << floor(Time(arr, n, Emptypipe)) << " Hours";
 
    return 0;
}


Java
// Java implementation of
// above approach
import java.io.*;
 
class GFG
{
     
// Function to calculate the time
static float Time(float arr[], int n,
                  float Emptypipe)
{
    float fill = 0;
    for (int i = 0; i < n; i++)
        fill += 1 / arr[i];
 
    fill = fill - (1 / (float)Emptypipe);
 
    return 1 / fill;
}
 
// Driver Code
public static void main (String[] args)
{
    float arr[] = { 12, 14 };
    float Emptypipe = 30;
    int n = arr.length;
     
    System.out.println((int)(Time(arr, n,
                        Emptypipe)) + " Hours");
}
}
 
// This code is contributed
// by inder_verma.


Python3
# Python3 implementation of
# above approach
 
# Function to calculate the time
def Time(arr, n, Emptypipe) :
 
    fill = 0
    for i in range(0,n) :
        fill += (1 / arr[i])
 
    fill = fill - (1 / float(Emptypipe))
 
    return int(1 / fill)
 
 
# Driver Code
if __name__=='__main__':
    arr = [ 12, 14 ]
    Emptypipe = 30
    n = len(arr)
    print((Time(arr, n, Emptypipe))
          , "Hours")
 
# This code is contributed by
# Smitha Dinesh Semwal


C#
// C# implementation of
// above approach
using System;
 
class GFG
{
     
// Function to calculate the time
static float Time(float []arr, int n,
                  float Emptypipe)
{
    float fill = 0;
    for (int i = 0; i < n; i++)
        fill += 1 / arr[i];
 
    fill = fill - (1 / (float)Emptypipe);
 
    return 1 / fill;
}
 
// Driver Code
public static void Main ()
{
    float []arr = { 12, 14 };
    float Emptypipe = 30;
    int n = arr.Length;
     
    Console.WriteLine((int)(Time(arr, n,
                             Emptypipe)) +
                                " Hours");
}
}
 
// This code is contributed
// by inder_verma.


PHP


Javascript


输出:
8 Hours