📌  相关文章
📜  最大限度地减少将N根长度的棒切成N根单位长度的棒所需的切割次数

📅  最后修改于: 2021-04-22 03:37:57             🧑  作者: Mango

给定一个表示给定棒的长度的整数N ,任务是最小化将棒分割成单位长度的片段所需的时间,因为在任何时间实例都可以对棒的任何部分进行一次切割。

例子:

方法:
由于我们可以在特定的时间切割一次棒的任何部分,因此我们需要在每次切割后将其最大化。因此,我们将在第一次切割时将木棍切成尽可能长的两个部分。在下一个实例中,在下一次切割中将两个获得的部分进一步切割成两个最长的部分。重复此步骤,直到获得N个单位。

因此,将N长棒分成1个单位所需的最短时间为ceil(log 2 N)

下面是上述方法的实现:

C++
// C++ program to find minimum
// time required to split a
// stick of N length into
// unit pieces
 
#include 
using namespace std;
 
// Function to return the
// minimum time required
// to split stick of N into
// length into unit pieces
int min_time_to_cut(int N)
{
    if (N == 0)
        return 0;
    // Return the minimum
    // unit of time required
    return ceil(log2(N));
}
// Driver Code
int main()
{
    int N = 100;
    cout << min_time_to_cut(N);
    return 0;
}


Java
// Java program to find minimum
// time required to split a
// stick of N length into
// unit pieces
import java.lang.*;
 
class GFG{
     
// Function to return the
// minimum time required
// to split stick of N into
// length into unit pieces
static int min_time_to_cut(int N)
{
    if (N == 0)
        return 0;
         
    // Return the minimum
    // unit of time required
    return (int)Math.ceil(Math.log(N) /
                          Math.log(2));
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 100;
    System.out.print(min_time_to_cut(N));
}
}
 
// This code is contributed by rock_cool


Python3
# Python3 program to find minimum
# time required to split a stick
# of N length into unit pieces
import math
 
# Function to return the
# minimum time required
# to split stick of N into
# length into unit pieces
def min_time_to_cut(N):
     
    if (N == 0):
        return 0
         
    # Return the minimum
    # unit of time required
    return int(math.log2(N)) + 1
 
# Driver Code
N = 100
 
print(min_time_to_cut(N))
 
# This code is contributed by Vishal Maurya


C#
// C# program to find minimum
// time required to split a
// stick of N length into
// unit pieces
using System;
class GFG{
     
// Function to return the
// minimum time required
// to split stick of N into
// length into unit pieces
static int min_time_to_cut(int N)
{
    if (N == 0)
        return 0;
         
    // Return the minimum
    // unit of time required
    return (int)Math.Ceiling(Math.Log(N) /
                             Math.Log(2));
}
 
// Driver Code
public static void Main()
{
    int N = 100;
    Console.Write(min_time_to_cut(N));
}
}
 
// This code is contributed by Code_Mech


Javascript


输出:
7

时间复杂度: O(1)
辅助空间: O(1)