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

📅  最后修改于: 2021-05-14 08:08:25             🧑  作者: Mango

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

例子:

方法:请遵循以下步骤:

  • 初始化一个变量,例如ans ,以存储将所有数组元素转换为0的最低成本。
  • 计算并存储仅由0 s组成的所有子数组的长度,并将其存储在向量中,并对向量进行升序排序。
  • 现在,仅计算由1 s组成的子数组的数量。
  • 使用变量i遍历给定的数组,其中i表示Y cost操作的数量,并执行以下操作:
    • 对于成本Y的每个可能的工序数,通过执行X工序找到成本。
    • 由于在将两组1之间的位设置为1时,组的总数减少了,因此请首先合并两个连续1 s的组以减少最小操作数。
    • 查找完成每个索引的上述步骤的最低成本作为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


输出:
14

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