📌  相关文章
📜  最小化将二进制字符串的所有字符转换为0的成本

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

给定一个二进制字符串str ,两个整数数组R []C []的大小为N。将所有字符从索引i翻转到R [i]需要C [i]成本。任务是使将给定的二进制字符串转换为仅0所需的成本最小化。

例子:

方法:可以使用贪婪技术解决问题。这个想法是从左到右遍历给定的字符串,并检查当前字符是否为非零字符。如果发现是正确的,则将所有字符从当前索引(= i)翻转到第R [i]索引。请按照以下步骤解决问题:

  • 初始化一个变量,例如flip ,以存储当前字符可以翻转的次数。
  • 创建一个优先级队列,例如说pq,以将当前字符右侧的字符索引范围存储在翻转值大于0的当前字符的右侧。
  • 初始化一个变量,例如cost,以存储获得所需字符串的最低成本。
  • 遍历给定的字符串,并检查当前字符是否为“ 1 ”。如果确定为真,则将范围i中的所有字符翻转到R [i]并将cost的值增加C [i]
  • 最后,打印cost的值。

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to get the minimum
// Cost to convert all characters
// of given string to 0s
int minCost(string str, int N, int R[], int C[])
{
    // Stores the range of indexes
    // of characters that need
    // to be flipped
    priority_queue, greater > pq;
 
    // Stores the number of times
    // current character is flipped
    int flip = 0;
 
    // Stores minimum cost to get
    // the required string
    int cost = 0;
 
    // Traverse the given string
    for (int i = 0; i < N; i++)
    {
        // Remove all value from pq
        // whose value is less than i
        while (pq.size() > 0 and pq.top() < i)
        {
            pq.pop();
 
            // Update flip
            flip--;
        }
 
        // If current character
        // is flipped odd times
        if (flip % 2 == 1)
        {
            str[i] = '1' - str[i] + '0';
        }
 
        // If current character contains
        // non-zero value
        if (str[i] == '1')
        {
            // Update flip
            flip++;
 
            // Update cost
            cost += C[i];
 
            // Append R[i] into pq
            pq.push(R[i]);
        }
    }
    return cost;
}
 
// Driver Code
int main()
{
    string str = "1010";
    int R[] = { 1, 2, 2, 3 };
    int C[] = { 3, 1, 2, 3 };
    int N = str.length();
   
    // Function call
    cout << minCost(str, N, R, C);
}


Java
// Java program to implement
// the above approach
 
import java.util.*;
import java.lang.*;
import java.io.*;
 
class GFG {
 
    // Function to get the minimum
    // Cost to convert all characters
    // of given string to 0s
    public static int minCost(String s,
                              int R[],
                              int C[],
                              int N)
    {
        char ch[] = s.toCharArray();
 
        // Stores the range of indexes
        // of characters that need
        // to be flipped
        PriorityQueue pq = new PriorityQueue<>();
 
        // Stores the number of times
        // current character is flipped
        int flip = 0;
 
        // Stores minimum cost to get
        // the required string
        int cost = 0;
 
        // Traverse the given string
        for (int i = 0; i < N; i++) {
 
            // Remove all value from pq
            // whose value is less than i
 
            while (pq.size() > 0 && pq.peek() < i)
            {
                pq.poll();
 
                // Update flip
                flip--;
            }
 
            // Get the current number
            int cn = ch[i] - '0';
 
            // If current character
            // is flipped odd times
            if (flip % 2 == 1)
                cn = 1 - cn;
 
            // If current character contains
            // non-zero value
            if (cn == 1)
            {
                // Update flip
                flip++;
 
                // Update cost
                cost += C[i];
 
                // Append R[i] into pq
                pq.add(R[i]);
            }
        }
        return cost;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int N = 4;
        String s = "1010";
        int R[] = { 1, 2, 2, 3 };
        int C[] = { 3, 1, 2, 3 };
 
        // Function call
        System.out.println(minCost(s, R, C, N));
    }
}


Python3
# Python3 program to implement
# the above approach
 
# Function to get the minimum
# Cost to convert all characters
# of given string to 0s
def minCost(s, R, C, N) :
    ch = list(s)
  
    # Stores the range of indexes
    # of characters that need
    # to be flipped
    pq = []
  
    # Stores the number of times
    # current character is flipped
    flip = 0
  
    # Stores minimum cost to get
    # the required string
    cost = 0
  
    # Traverse the given string
    for i in range(N) :
          
        # Remove all value from pq
        # whose value is less than i
        while (len(pq) > 0 and pq[0] < i) :
     
            pq.pop(0);
  
            # Update flip
            flip -= 1
  
        # Get the current number
        cn = ord(ch[i]) - ord('0')
  
        # If current character
        # is flipped odd times
        if (flip % 2 == 1) :
            cn = 1 - cn
  
        # If current character contains
        # non-zero value
        if (cn == 1) :
              
            # Update flip
            flip += 1
  
            # Update cost
            cost += C[i]
  
            # Append R[i] into pq
            pq.append(R[i])
              
    return cost
   
  # Driver code
N = 4
s = "1010"
R = [ 1, 2, 2, 3 ]
C = [ 3, 1, 2, 3 ]
 
# Function call
print(minCost(s, R, C, N))
 
# This code is contributed by divyeshrabadiya07.


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to get the minimum
// Cost to convert all characters
// of given string to 0s
public static int minCost(String s, int []R,
                           int []C, int N)
{
    char []ch = s.ToCharArray();
 
    // Stores the range of indexes
    // of characters that need
    // to be flipped
    Queue pq = new Queue();
 
    // Stores the number of times
    // current character is flipped
    int flip = 0;
 
    // Stores minimum cost to get
    // the required string
    int cost = 0;
 
    // Traverse the given string
    for(int i = 0; i < N; i++)
    {
         
        // Remove all value from pq
        // whose value is less than i
        while (pq.Count > 0 && pq.Peek() < i)
        {
            pq.Dequeue();
 
            // Update flip
            flip--;
        }
 
        // Get the current number
        int cn = ch[i] - '0';
 
        // If current character
        // is flipped odd times
        if (flip % 2 == 1)
            cn = 1 - cn;
 
        // If current character contains
        // non-zero value
        if (cn == 1)
        {
             
            // Update flip
            flip++;
 
            // Update cost
            cost += C[i];
 
            // Append R[i] into pq
            pq.Enqueue(R[i]);
             
        }
    }
    return cost;
}
 
// Driver Code
public static void Main(String[] args)
{
    int N = 4;
    String s = "1010";
    int []R = { 1, 2, 2, 3 };
    int []C = { 3, 1, 2, 3 };
 
    // Function call
    Console.WriteLine(minCost(s, R, C, N));
}
}
 
// This code is contributed by Amit Katiyar


输出
4

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