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

📅  最后修改于: 2021-04-21 22:54:18             🧑  作者: 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


输出:
4






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