📌  相关文章
📜  最小化将所有数组元素转换为 0 的成本

📅  最后修改于: 2021-10-25 11:26:38             🧑  作者: Mango

给定两个整数XY以及一个长度为N的二进制数组arr[]其第一个和最后一个元素为1 ,任务是最小化将所有数组元素转换为0的成本,其中XY表示转换子数组的成本的所有1秒至0秒和分别任何元素转换为0的成本。

例子:

方法:按照以下步骤操作:

  • 初始化一个变量,比如ans ,以存储将所有数组元素转换为0的最小成本。
  • 计算并存储所有仅由0组成的子数组的长度,并将其存储在一个向量中,并按升序对向量进行排序。
  • 现在,计算仅由1组成的子数组的数量。
  • 使用变量i遍历给定数组,其中i表示Y成本操作的数量,并执行以下操作:
    • 对于成本为Y 的每个可能的操作次数,通过执行X操作来找到成本。
    • 由于在两组1之间设置位时,组的总数会减少,因此首先合并两组连续的1以减少最小操作次数。
    • 为每个索引找到完成上述步骤的最小成本作为currCost并更新ans以存储anscurrCost的最小值。
  • 完成上述步骤后,打印ans的值作为最小成本。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to calculate the minimum cost
// of converting all array elements to 0s
void minimumCost(int* binary, int n,
                 int a, int b)
{
    // Stores subarrays of 0s only
    vector groupOfZeros;
 
    int len = 0, i = 0;
    bool increment_need = true;
 
    // Traverse the array
    while (i < n) {
        increment_need = true;
 
        // If consecutive 0s occur
        while (i < n && binary[i] == 0) {
            len++;
            i++;
            increment_need = false;
        }
 
        // Increment if needed
        if (increment_need == true) {
            i++;
        }
 
        // Push the current length of
        // consecutive 0s in a vector
        if (len != 0) {
            groupOfZeros.push_back(len);
        }
 
        // Update lengths as 0
        len = 0;
    }
 
    // Sorting vector
    sort(groupOfZeros.begin(),
         groupOfZeros.end());
 
    i = 0;
    bool found_ones = false;
 
    // Stores the number of
    // subarrays consisting of 1s
    int NumOfOnes = 0;
 
    // Traverse the array
    while (i < n) {
        found_ones = false;
 
        // If current element is 1
        while (i < n && binary[i] == 1) {
            i++;
            found_ones = true;
        }
        if (found_ones == false)
            i++;
 
        // Otherwise
        else
 
            // Increment count of
            // consecutive ones
            NumOfOnes++;
    }
 
    // Stores the minimum cost
    int ans = INT_MAX;
 
    // Traverse the array
    for (int i = 0; i < n; i++) {
 
        int curr = 0, totalOnes = NumOfOnes;
 
        // First element
        if (i == 0) {
            curr = totalOnes * a;
        }
        else {
 
            int mark = i, num_of_changes = 0;
 
            // Traverse the subarray sizes
            for (int x : groupOfZeros) {
 
                if (mark >= x) {
                    totalOnes--;
                    mark -= x;
 
                    // Update cost
                    num_of_changes += x;
                }
                else {
                    break;
                }
            }
 
            // Cost of performing X
            // and Y operations
            curr = (num_of_changes * b)
                   + (totalOnes * a);
        }
 
        // Find the minimum cost
        ans = min(ans, curr);
    }
 
    // Print the minimum cost
    cout << ans;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 1, 1, 0, 1, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int X = 10, Y = 4;
 
    // Function Call
    minimumCost(arr, N, X, Y);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG{
 
// Function to calculate the minimum cost
// of converting all array elements to 0s
public static void minimumCost(int[] binary, int n,
                               int a, int b)
{
     
    // Stores subarrays of 0s only
    List groupOfZeros = new ArrayList();
 
    int len = 0, i = 0;
    boolean increment_need = true;
 
    // Traverse the array
    while (i < n)
    {
        increment_need = true;
 
        // If consecutive 0s occur
        while (i < n && binary[i] == 0)
        {
            len++;
            i++;
            increment_need = false;
        }
 
        // Increment if needed
        if (increment_need == true)
        {
            i++;
        }
 
        // Push the current length of
        // consecutive 0s in a vector
        if (len != 0)
        {
            groupOfZeros.add(len);
        }
 
        // Update lengths as 0
        len = 0;
    }
 
    // Sorting List
    Collections.sort(groupOfZeros);
 
    i = 0;
    boolean found_ones = false;
 
    // Stores the number of
    // subarrays consisting of 1s
    int NumOfOnes = 0;
 
    // Traverse the array
    while (i < n)
    {
        found_ones = false;
 
        // If current element is 1
        while (i < n && binary[i] == 1)
        {
            i++;
            found_ones = true;
        }
        if (found_ones == false)
            i++;
 
        // Otherwise
        else
 
            // Increment count of
            // consecutive ones
            NumOfOnes++;
    }
 
    // Stores the minimum cost
    int ans = Integer.MAX_VALUE;
 
    // Traverse the array
    for(int i1 = 0; i1 < n; i1++)
    {
        int curr = 0, totalOnes = NumOfOnes;
 
        // First element
        if (i1 == 0)
        {
            curr = totalOnes * a;
        }
        else
        {
            int mark = i1, num_of_changes = 0;
 
            // Traverse the subarray sizes
            for(int x : groupOfZeros)
            {
                if (mark >= x)
                {
                    totalOnes--;
                    mark -= x;
                     
                    // Update cost
                    num_of_changes += x;
                }
                else
                {
                    break;
                }
            }
 
            // Cost of performing X
            // and Y operations
            curr = (num_of_changes * b) +
                        (totalOnes * a);
        }
 
        // Find the minimum cost
        ans = Math.min(ans, curr);
    }
 
    // Print the minimum cost
    System.out.println(ans);
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 1, 1, 1, 0, 1, 1 };
    int N = 6;
    int X = 10, Y = 4;
     
    // Function Call
    minimumCost(arr, N, X, Y);
}
}
 
// This code is contributed by RohitOberoi


Python3
# Python3 program for the above approach
import sys
 
# Function to calculate the minimum cost
# of converting all array elements to 0s
def minimumCost(binary, n,
                a,  b):
 
    # Stores subarrays of 0s only
    groupOfZeros = []
 
    length = 0
    i = 0
    increment_need = True
 
    # Traverse the array
    while (i < n):
        increment_need = True
 
        # If consecutive 0s occur
        while (i < n and binary[i] == 0):
            length += 1
            i += 1
            increment_need = False
 
        # Increment if needed
        if (increment_need == True):
            i += 1
 
        # Push the current length of
        # consecutive 0s in a vector
        if (length != 0):
            groupOfZeros.append(length)
 
        # Update lengths as 0
        length = 0
 
    # Sorting vector
    groupOfZeros.sort()
 
    i = 0
    found_ones = False
 
    # Stores the number of
    # subarrays consisting of 1s
    NumOfOnes = 0
 
    # Traverse the array
    while (i < n):
        found_ones = False
 
        # If current element is 1
        while (i < n and binary[i] == 1):
            i += 1
            found_ones = True
 
        if (found_ones == False):
            i += 1
 
        # Otherwise
        else:
 
            # Increment count of
            # consecutive ones
            NumOfOnes += 1
 
    # Stores the minimum cost
    ans = sys.maxsize
 
    # Traverse the array
    for i in range(n):
 
        curr = 0
        totalOnes = NumOfOnes
 
        # First element
        if (i == 0):
            curr = totalOnes * a
 
        else:
 
            mark = i
            num_of_changes = 0
 
            # Traverse the subarray sizes
            for x in groupOfZeros:
 
                if (mark >= x):
                    totalOnes -= 1
                    mark -= x
 
                    # Update cost
                    num_of_changes += x
 
                else:
                    break
 
            # Cost of performing X
            # and Y operations
            curr = ((num_of_changes * b)
                    + (totalOnes * a))
 
        # Find the minimum cost
        ans = min(ans, curr)
 
    # Print the minimum cost
    print(ans)
 
# Driver Code
if __name__ == "__main__":
    arr = [1, 1, 1, 0, 1, 1]
    N = len(arr)
    X = 10
    Y = 4
 
    # Function Call
    minimumCost(arr, N, X, Y)
 
    # This code is contributed by chitranayal


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to calculate the minimum cost
// of converting all array elements to 0s
public static void minimumCost(int[] binary, int n,
                               int a, int b)
{
   
    // Stores subarrays of 0s only
    List groupOfZeros = new List();
 
    int len = 0, i = 0;
    bool increment_need = true;
 
    // Traverse the array
    while (i < n)
    {
        increment_need = true;
 
        // If consecutive 0s occur
        while (i < n && binary[i] == 0)
        {
            len++;
            i++;
            increment_need = false;
        }
 
        // Increment if needed
        if (increment_need == true)
        {
            i++;
        }
 
        // Push the current length of
        // consecutive 0s in a vector
        if (len != 0)
        {
            groupOfZeros.Add(len);
        }
 
        // Update lengths as 0
        len = 0;
    }
 
    // Sorting List
    groupOfZeros.Sort();
 
    i = 0;
    bool found_ones = false;
 
    // Stores the number of
    // subarrays consisting of 1s
    int NumOfOnes = 0;
 
    // Traverse the array
    while (i < n)
    {
        found_ones = false;
 
        // If current element is 1
        while (i < n && binary[i] == 1)
        {
            i++;
            found_ones = true;
        }
        if (found_ones == false)
            i++;
 
        // Otherwise
        else
 
            // Increment count of
            // consecutive ones
            NumOfOnes++;
    }
 
    // Stores the minimum cost
    int ans = int.MaxValue;
 
    // Traverse the array
    for(int i1 = 0; i1 < n; i1++)
    {
        int curr = 0, totalOnes = NumOfOnes;
 
        // First element
        if (i1 == 0)
        {
            curr = totalOnes * a;
        }
        else
        {
            int mark = i1, num_of_changes = 0;
 
            // Traverse the subarray sizes
            foreach(int x in groupOfZeros)
            {
                if (mark >= x)
                {
                    totalOnes--;
                    mark -= x;
                     
                    // Update cost
                    num_of_changes += x;
                }
                else
                {
                    break;
                }
            }
 
            // Cost of performing X
            // and Y operations
            curr = (num_of_changes * b) +
                        (totalOnes * a);
        }
 
        // Find the minimum cost
        ans = Math.Min(ans, curr);
    }
 
    // Print the minimum cost
    Console.WriteLine(ans);
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = { 1, 1, 1, 0, 1, 1 };
    int N = 6;
    int X = 10, Y = 4;
     
    // Function Call
    minimumCost(arr, N, X, Y);
}
}
 
// This code is contributed by Amit Katiyar


Javascript


输出:
14

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

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程