CodeForces 3D Least Cost Bracket Sequence (贪心+优先队列)

探讨了一种算法,该算法通过替换特定模式中的问号为括号,并确保括号匹配的同时达到最小成本。介绍了使用优先队列实现的贪心策略。

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.
Sample test(s)
Input
(??)
1 2
2 8
Output
4
()()

题意:给出一堆左右括号和问号,还有各个问号变成左右括号的花费,问你是否能将问号变成左右括号,使其配对,且花费最少。
题解:进行贪心策略,先假设所有问号都是右括号,然后若右括号过多(要使得串能够匹配,每一个字符左边的字串中左括号个数必须大于等于右括号的个数),利用优先队列把左右括号花费差最大的变成左括号,这样就可以使花费最小了,若最后括号数不能平衡,则输出-1

package org.lf.algorithms.least.bracket;

import java.util.PriorityQueue;
import java.util.Scanner;

public class LeastBracket {
    int x[] = null ;
    int y[] = null ;
    StringBuffer sb = null ;
    int result = 0 ;
    public LeastBracket(){

    }
    public void input(){
        Scanner scan = new Scanner(System.in) ;
        //读入表达式
        sb = new StringBuffer(scan.next()) ;
        x = new int[sb.length()] ;
        y = new int[sb.length()] ;
        int i = 0 ;
        while(i<sb.length()){
            if(sb.charAt(i)=='?'){
                int a = scan.nextInt() ;
                int b = scan.nextInt() ;
                x[i] = a ;
                y[i] = b ;
            }
            i++ ;
        }
    }

    public void process(){
        PriorityQueue<Point> pq = new PriorityQueue<Point>() ;
        int i = 0 ;
        int count = 0 ;

        while(i<sb.length()){
            if(sb.charAt(i)=='('){
                count++ ;
            }else if(sb.charAt(i)==')'){
                count-- ;
            }else{
                Point p = new Point(i,y[i] - x[i]) ;
                pq.add(p) ;
                sb.replace(i, i+1, ")") ;
                count-- ;
                result = result + y[i] ;
            }

            if(count < 0){
                if(pq.isEmpty()){
                    break ;
                }
                Point temp = pq.remove() ;
                pq.remove() ;
                sb.replace(temp.num, temp.num+1, "(") ;
                result = result - temp.val ;
                count = count + 2 ;
            }

            i++ ;
        }

        if(count==0){
            System.out.println(result) ;
            System.out.println(sb) ;
        }else{
            System.out.println(-1);
        }

    }
    public static void main(String[] args) {
        LeastBracket lb = new LeastBracket() ;
        lb.input() ;
        lb.process() ;

    }

}

class Point implements Comparable<Point>{
    int val ;
    int num ;
    public Point(int num,int val){
        this.num = num ;
        this.val = val ;
    }
    public int compareTo(Point point) {
        //降序排列
        if(this.val > point.val)
            return -1 ;
        if(this.val < point.val)
            return 1 ;
        return 0 ;
    }
}
当前提供的引用内容并未提及关于Codeforces比赛M1的具体时间安排[^1]。然而,通常情况下,Codeforces的比赛时间会在其官方网站上提前公布,并提供基于不同时区的转换工具以便参赛者了解具体开赛时刻。 对于Codeforces上的赛事而言,如果一场名为M1的比赛被计划举行,则它的原始时间一般按照UTC(协调世界时)设定。为了得知该场比赛在UTC+8时区的确切开始时间,可以遵循以下逻辑: - 前往Codeforces官网并定位至对应比赛页面。 - 查看比赛所标注的标准UTC起始时间。 - 将此标准时间加上8小时来获取对应的北京时间(即UTC+8)。 由于目前缺乏具体的官方公告链接或者确切日期作为依据,无法直接给出Codeforces M1比赛于UTC+8下的实际发生时段。建议定期访问Codeforces平台查看最新动态更新以及确认最终版程表信息。 ```python from datetime import timedelta, datetime def convert_utc_to_bj(utc_time_str): utc_format = "%Y-%m-%dT%H:%M:%SZ" bj_offset = timedelta(hours=8) try: # 解析UTC时间为datetime对象 utc_datetime = datetime.strptime(utc_time_str, utc_format) # 转换为北京时区时间 beijing_time = utc_datetime + bj_offset return beijing_time.strftime("%Y-%m-%d %H:%M:%S") except ValueError as e: return f"错误:{e}" # 示例输入假设某场Codeforces比赛定于特定UTC时间 example_utc_start = "2024-12-05T17:35:00Z" converted_time = convert_utc_to_bj(example_utc_start) print(f"Codeforces比赛在北京时间下将是:{converted_time}") ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值