📜  生成平衡括号序列所需的最低成本

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

给定一个长度为N的字符串str ,代表一个括号序列,以及两个整数AB ,任务是通过执行以下任意数量的移动(可能为零)来找到从str 中获得常规括号序列所需的最小成本类型:

  • 从字符串删除一个字符,成本为A
  • 在所述字符串具有成本B的端部取下字符串和附加的字符。

例子:

处理方法:按照以下步骤解决问题:

  • 计算给定字符串中打开‘(‘和关闭‘)’括号的频率,并存储两者中更频繁的一个。
  • 最低成本至少是一个 * (abs(open – count)) ,因为需要删除这些括号以平衡字符串。
  • 计算字符串中不平衡的左括号和右括号的数量。如果开括号过多,则通过多余开括号的计数来减少不平衡的开括号数量。同样,如果右括号过多,则减少不平衡右括号的数量。
  • 现在,计算删除所有不平衡的开括号和不平衡的闭括号成本,以及删除不平衡的闭括号并将它们添加到末尾成本。比较两个成本中的最小值并将其添加到答案中。
  • 因此,生成平衡括号序列所需的最低成本由以下等式给出:

下面是上述方法的实现:

C++
// C++ Program to implement
// the above approach
#include 
using namespace std;
 
// Function to calculate the minimum cost
// required to generate a balanced bracket
// sequence
void minCost(string str, int a, int b)
{
    // Stores the count of
    // unbalanced open brackets
    int openUnbalanced = 0;
 
    // Stores the count of
    // unbalanced closed brackets
    int closedUnbalanced = 0;
 
    // Stores the count of
    // open brackets
    int openCount = 0;
 
    // Stores the count of
    // closed brackets
    int closedCount = 0;
 
    for (int i = 0; str[i] != '\0'; i++) {
 
        // If open brace is encountered
        if (str[i] == '(') {
            openUnbalanced++;
            openCount++;
        }
 
        // Otherwise
        else {
 
            // If no unbalanced open
            // brackets are present
            if (openUnbalanced == 0)
 
                // Increase count of
                // unbalanced closed brackets
                closedUnbalanced++;
 
            // Otherwise
            else
 
                // Reduce count of
                // unbalanced open brackets
                openUnbalanced--;
 
            // Increase count of
            // closed brackets
            closedCount++;
        }
    }
 
    // Calculate lower bound of minimum cost
    int result = a * (abs(openCount
                          - closedCount));
 
    // Reduce excess open or closed brackets
    // to prevent counting them twice
    if (closedCount > openCount)
        closedUnbalanced
            -= (closedCount - openCount);
 
    if (openCount > closedCount)
        openUnbalanced
            -= (openCount - closedCount);
 
    // Update answer by adding minimum of
    // removing both unbalanced open and
    // closed brackets or inserting closed
    // unbalanced brackets to end of string
    result += min(a * (openUnbalanced
                       + closedUnbalanced),
                  b * closedUnbalanced);
 
    // Print the result
    cout << result << endl;
}
 
// Driver Code
int main()
{
    string str = "))()(()()(";
    int A = 1, B = 3;
    minCost(str, A, B);
 
    return 0;
}


Java
// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
 
// Function to calculate the minimum cost
// required to generate a balanced bracket
// sequence
static void minCost(String str, int a, int b)
{
     
    // Stores the count of
    // unbalanced open brackets
    int openUnbalanced = 0;
 
    // Stores the count of
    // unbalanced closed brackets
    int closedUnbalanced = 0;
 
    // Stores the count of
    // open brackets
    int openCount = 0;
 
    // Stores the count of
    // closed brackets
    int closedCount = 0;
 
    for(int i = 0; i < str.length(); i++)
    {
 
        // If open brace is encountered
        if (str.charAt(i) == '(')
        {
            openUnbalanced++;
            openCount++;
        }
 
        // Otherwise
        else
        {
             
            // If no unbalanced open
            // brackets are present
            if (openUnbalanced == 0)
 
                // Increase count of
                // unbalanced closed brackets
                closedUnbalanced++;
 
            // Otherwise
            else
 
                // Reduce count of
                // unbalanced open brackets
                openUnbalanced--;
 
            // Increase count of
            // closed brackets
            closedCount++;
        }
    }
 
    // Calculate lower bound of minimum cost
    int result = a * (Math.abs(openCount -
                             closedCount));
 
    // Reduce excess open or closed brackets
    // to prevent counting them twice
    if (closedCount > openCount)
        closedUnbalanced -= (closedCount - 
                               openCount);
 
    if (openCount > closedCount)
        openUnbalanced -= (openCount -
                         closedCount);
 
    // Update answer by adding minimum of
    // removing both unbalanced open and
    // closed brackets or inserting closed
    // unbalanced brackets to end of String
    result += Math.min(a * (openUnbalanced +
                            closedUnbalanced),
                        b * closedUnbalanced);
 
    // Print the result
    System.out.print(result + "\n");
}
 
// Driver Code
public static void main(String[] args)
{
    String str = "))()(()()(";
    int A = 1, B = 3;
     
    minCost(str, A, B);
}
}
 
// This code is contributed by amal kumar choubey


Python3
# Python3 program to implement
# the above approach
 
# Function to calculate the minimum cost
# required to generate a balanced bracket
# sequence
def minCost(str, a, b):
 
    # Stores the count of
    # unbalanced open brackets
    openUnbalanced = 0;
 
    # Stores the count of
    # unbalanced closed brackets
    closedUnbalanced = 0;
 
    # Stores the count of
    # open brackets
    openCount = 0;
 
    # Stores the count of
    # closed brackets
    closedCount = 0;
 
    for i in range(len(str)):
 
        # If open brace is encountered
        if (str[i] == '('):
            openUnbalanced += 1;
            openCount += 1;
         
        # Otherwise
        else:
 
            # If no unbalanced open
            # brackets are present
            if (openUnbalanced == 0):
 
                # Increase count of
                # unbalanced closed brackets
                closedUnbalanced += 1;
 
            # Otherwise
            else:
 
                # Reduce count of
                # unbalanced open brackets
                openUnbalanced -= 1;
 
            # Increase count of
            # closed brackets
            closedCount += 1;
         
    # Calculate lower bound of minimum cost
    result = a * (abs(openCount - closedCount));
 
    # Reduce excess open or closed brackets
    # to prevent counting them twice
    if (closedCount > openCount):
        closedUnbalanced -= (closedCount - openCount);
 
    if (openCount > closedCount):
        openUnbalanced -= (openCount - closedCount);
 
    # Update answer by adding minimum of
    # removing both unbalanced open and
    # closed brackets or inserting closed
    # unbalanced brackets to end of String
    result += min(a * (openUnbalanced +
                       closedUnbalanced),
                   b * closedUnbalanced);
 
    # Prthe result
    print(result);
 
# Driver Code
if __name__ == '__main__':
    str = "))()(()()(";
    A = 1; B = 3;
 
    minCost(str, A, B);
 
# This code is contributed by Rohit_ranjan


C#
// C# program to implement
// the above approach
using System;
class GFG{
 
// Function to calculate the minimum cost
// required to generate a balanced bracket
// sequence
static void minCost(String str, int a, int b)
{
     
    // Stores the count of
    // unbalanced open brackets
    int openUnbalanced = 0;
 
    // Stores the count of
    // unbalanced closed brackets
    int closedUnbalanced = 0;
 
    // Stores the count of
    // open brackets
    int openCount = 0;
 
    // Stores the count of
    // closed brackets
    int closedCount = 0;
 
    for(int i = 0; i < str.Length; i++)
    {
 
        // If open brace is encountered
        if (str[i] == '(')
        {
            openUnbalanced++;
            openCount++;
        }
 
        // Otherwise
        else
        {
             
            // If no unbalanced open
            // brackets are present
            if (openUnbalanced == 0)
 
                // Increase count of
                // unbalanced closed brackets
                closedUnbalanced++;
 
            // Otherwise
            else
 
                // Reduce count of
                // unbalanced open brackets
                openUnbalanced--;
 
            // Increase count of
            // closed brackets
            closedCount++;
        }
    }
 
    // Calculate lower bound of minimum cost
    int result = a * (Math.Abs(openCount -
                               closedCount));
 
    // Reduce excess open or closed brackets
    // to prevent counting them twice
    if (closedCount > openCount)
        closedUnbalanced -= (closedCount - 
                             openCount);
 
    if (openCount > closedCount)
        openUnbalanced -= (openCount -
                           closedCount);
 
    // Update answer by adding minimum of
    // removing both unbalanced open and
    // closed brackets or inserting closed
    // unbalanced brackets to end of String
    result += Math.Min(a * (openUnbalanced +
                           closedUnbalanced),
                       b * closedUnbalanced);
 
    // Print the result
    Console.Write(result + "\n");
}
 
// Driver Code
public static void Main(String[] args)
{
    String str = "))()(()()(";
    int A = 1, B = 3;
     
    minCost(str, A, B);
}
}
 
// This code is contributed by gauravrajput1


Javascript


输出:
4

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

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