Codeforces Beta Round #3 D. Least Cost Bracket Sequence(贪心,想法,好题)

该问题要求在给定的包含'(', ')', '?'的序列中,用最小代价将'?'替换为合适的括号以形成正确的括号序列。通过贪心策略,首先假设所有'?'都是')',然后遍历序列,当遇到计数器为负时,尝试从前查找'?'并将其替换为'(',以使序列有效。如果最后无法得到有效的括号序列,则输出-1。" 134130659,8658200,PCL计算平面与包围盒相交线的实现,"['PCL', '三维几何', '计算机视觉', 'C++编程']

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

D. Least Cost Bracket Sequence
time limit per test
1 second
memory limit per test
64 megabytes
input
standard input
output
standard output

This is yet another problem on regular bracket sequences.

A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.

For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.

Input

The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi(1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.

Output

Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second.

Print -1, if there is no answer. If the answer is not unique, print any of them. 

Examples
input
(??)
1 2
2 8
output
4
()()


参考博客链接


题意:

是给一个序列,序列里面会有左括号、问号、右括号。对于一个‘?’而言,可以将其替换为一个‘(’,也可以替换成一个‘)’,但是都有相应的代价。

问:如何替换使得代价最小。前提是替换之后的序列中,括号是匹配的。如果不能替换为一个括号匹配的序列则输出-1。



题解:

刚开始想的是动态规划,但是想想这个好像是有后效的,所以动态规划就作罢了。

然后就贪心吧。先假设所有的‘?’全部替换成右括号,然后按常规的办法去检测这个序列是否括号匹配。

所谓的常规的办法就是遍历这个序列,维护一个计数器cnt,当遇到左括号时计数器+1,遇到右括号时计数器-1

如果中途遇到cnt小于0的情况,则说明这个序列不是括号匹配的,但是在我们这里,右括号可能是‘?’变来的,所以当遇到cnt小于0时,则去看前面有没有‘?’变过来的右括号,如果没有,那就说明无论如何这个序列无法被替换为括号匹配的序列;如果有的话,则选取一个“最好”的由‘?’变过来的右括号,将其改为左括号,这样的话cnt又可以加2了。这里所谓的“最好”,就是贪心的过程。至于怎样的最好,就自己去想吧。

如果这样到最后cnt还大于0,则说明即使无法获得一个括号匹配的序列,输出-1即可。

1.将所有的问号替换为右括号

2.遍历序列,维护计数器

3.当遇到计数器小于0则考虑从前面找一个问号变成左括号而不是右括号




#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
#include<stack>
using namespace std;
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=n-1;i>=a;i--)
#define pb push_back
#define fi first
#define se second
typedef vector<int> VI;
typedef long long ll;
typedef pair<int,int> PII;
const int maxn=1e6+100;
struct node
{
    int v,p;
    bool operator <(const node& b)const{
        return v<b.v;
    }
    node(int x=0,int y=0):v(x),p(y) {}
};
priority_queue<node> q;
char s[maxn];
int main()
{
    scanf("%s",s+1);
    int l=(int)strlen(s+1);
    int cnt=0;
    ll ans=0;
    rep(i,1,l+1)
    {
        if(s[i]=='?')
        {
            int a,b;
            scanf("%d%d",&a,&b);
            ans+=b;
            if(cnt>0)
                q.push(node(b-a,i)),cnt--,s[i]=')';
            else
            {
                q.push(node(b-a,i));
                cnt--;
                s[i]=')';
                while(cnt<0)
                {
                    if(q.empty())
                    {
                        puts("-1");
                        return 0;
                    }
                    node t=q.top();
                    q.pop();
                    ans-=t.v;
                    s[t.p]='(';
                    cnt+=2;
                    
                }
            }
        }
        else if(s[i]=='(') cnt++;
        else if(s[i]==')')
        {
            cnt--;
            while(cnt<0)
            {
                if(q.empty())
                {
                    puts("-1");
                    return 0;
                }
                node t=q.top();
                q.pop();
                ans-=t.v;
                s[t.p]='(';
                cnt+=2;
            }
        }
    }
    if(cnt) puts("-1");
    else
    {
        printf("%lld\n",ans);
        printf("%s\n",s+1);
    }
    return 0;
}

### 关于 Codeforces Round 839 Div 3目与解答 #### 目概述 Codeforces Round 839 Div 3 是一场面向不同编程水平参赛者的竞赛活动。这类比赛通常包含多个难度层次分明的问,旨在测试选手的基础算法知识以及解决问的能力。 对于特定的比赛问及其解决方案,虽然没有直接提及 Codeforces Round 839 Div 3 的具体细节[^1],但是可以根据以往类似的赛事结构来推测该轮次可能涉及的内容类型: - **输入处理**:给定一组参数作为输入条件,这些参数定义了待解决的任务范围。 - **逻辑实现**:基于输入构建满足一定约束条件的结果集。 - **输出格式化**:按照指定的方式呈现最终答案。 考虑到提供的参考资料中提到的其他几场赛事的信息[^2][^3],可以推断出 Codeforces 圆桌会议的一般模式是围绕着组合数学、图论、动态规划等领域展开挑战性的编程任务。 #### 示例解析 以一个假设的例子说明如何应对此类竞赛中的一个问。假设有如下描述的一个简单排列生成问: > 对于每一个测试案例,输出一个符合条件的排列——即一系列数字组成的集合。如果有多种可行方案,则任选其一给出即可。 针对上述要求的一种潜在解法可能是通过随机打乱顺序的方式来获得不同的合法排列形式之一。下面是一个 Python 实现示例: ```python import random def generate_permutation(n, m, k): # 创建初始序列 sequence = list(range(1, n + 1)) # 执行洗牌操作得到新的排列 random.shuffle(sequence) return " ".join(map(str, sequence[:k])) # 测试函数调用 print(generate_permutation(5, 2, 5)) # 输出类似于 "4 1 5 2 3" ``` 此代码片段展示了怎样创建并返回一个长度为 `k` 的随机整数列表,其中元素取自 `[1..n]` 这个区间内,并且保证所有成员都是唯一的。需要注意的是,在实际比赛中应当仔细阅读官方文档所提供的精确规格说明,因为这里仅提供了一个简化版的方法用于解释概念。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值