Balanced Sequence

本文介绍了一种针对由括号组成的字符串进行处理与组合的算法。该算法旨在通过特定的排序策略,使得由多个此类字符串组合而成的新串中包含最多的平衡括号子串,并详细解释了实现这一目标的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

题目原址:http://192.168.49.228/upload/file/20180723/20180723180123_70502.pdf

题目大意:给n个字符串,每个字符串只含有’(’ ‘)’,题目给了一些条件:

+ if it is the empty string 
+ if A and B are balanced, AB is balanced, 
+ if A is balanced, (A) is balanced. 
这样的是正规的串,组合这n个串,形成新的串,使得这样的正规的子串最多,不要求子串是连续的。输出符合的子串的总长度。

学习后,了解到:

   对每个串处理删除掉形如”()”这样的子串,最后剩下的子串只会是三种情形。

  1. 全部是’(’ 。
  2. 全部是’)’。
  3. 是”))))((((“这样的。

对剩下左右括号数量统计下来。 
  接下来就是对n个串排序,使得新组成的正规子串最多。 
  可以发现形如”((((((“这样的串应当放最前。”))))((((((“这样串分两类,’(‘多于’)’的放靠前,’(‘少于’)’放靠后面。”))))))))”这样的放最后。

   “((((“和”))))”好理解为什么这样子安排,”))((((“这样的就可以理解为,要尽可能的吧’(‘放在总体的左边,’)’放在总体的右边,当达到最极致的情况就会使得括号匹配的数量尽可能多。

cmp函数中部分条件只能“感觉”是最优的,但不能证明。

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct node
{
    int l;
    int r;
    int ans;
}a[100010];
int cmp(node a,node b)
{
    if(a.l<=a.r&&b.l>b.r) //)少(多 > )多(少
        return true;///不变
    if(a.l>a.r&&b.l<=b.r) //)多(少 < )少(多
        return false;///让a,b交换
    if(a.l<=a.r&&b.l<=b.r)//)少(多   )少(多
        return a.l<b.l;   //)少的放前面
    if(a.l>=a.r &&b.l>b.r)
        return a.r>b.r;       //(多的优先
}
int main()
{
    int f;
    char q[100010];
    
    scanf("%d", &f);
    while(f--){
        int n ;
        scanf("%d", &n);
        for(int i = 1; i <= n; i ++){
            scanf("%s", q);
            int len = strlen(q);
            a[i].l = a[i].r = a[i].ans = 0;
            for(int j = 0; j < len ; j ++){
                if(q[j] == '(')
                    a[i].l ++;
                else{
                    if(a[i].l > 0){
                        a[i].l --;
                        a[i].ans++;
                    }
                    else
                        a[i].r++;
                }
            }
        }
        
        sort(a + 1, a + n + 1, cmp);
        
        int r= 0, l = 0;
        
        for(int i = 1; i <= n; i ++){
            if(a[i].r > l){
                a[i].ans+=l;
                l = 0;
            }
            else{
                a[i].ans+=a[i].r;
                l-= a[i].r;
            }
            r+= a[i].ans;
            l+= a[i].l;
        }
        
        printf("%d\n", r * 2);
    }
    return 0;
}

 

Given an expression containing various types of parentheses, such as ( ), { }, and [], the task is to validate whether these parentheses are correctly matched and form a valid balanced sequence. A balanced sequence means that every opening parenthesis has a corresponding closing one, and no unmatched or improperly nested parentheses exist. To accomplish this, you can use a stack data structure. Here's a basic approach: 1. Iterate through each character in the expression. 2. If the character is an opening parenthesis (i.e., '(', '{', or '['), push it onto the stack. 3. If the character is a closing parenthesis, check if the stack is not empty. If it is, pop the top element from the stack and compare it with the current closing parenthesis. If they match (e.g., ')' matches '(', '{' matches '}', etc.), continue; otherwise, the expression is invalid and return False. 4. If the stack is empty after iterating through all characters, but there are still some closing parentheses left, it indicates unmatched opening parentheses and returns False. 5. If the stack is empty at the end, the expression is considered balanced and returns True. Here's a simple Python function demonstrating this logic: ```python def is_valid_parentheses(expression): brackets_map = { ")": "(", "}": "{", "]": "[" } stack = [] for char in expression: if char in brackets_map: if not stack or stack[-1] != brackets_map[char]: return False stack.pop() else: stack.append(char) return not stack # Example usage: expression_1 = "(){}[]" # Balanced, so True expression_2 = "({[})" # Unbalanced, so False expression_3 = "[(]" # Unmatched opening, so False print(is_valid_parentheses(expression_1)) # Output: True print(is_valid_parentheses(expression_2)) # Output: False print(is_valid_parentheses(expression_3)) # Output: False ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值