Codeforces远古场 Longest Regular Bracket Sequence (动态规划)

Longest Regular Bracket Sequence

题面翻译

给出一个括号序列,求出最长合法子串和它的数量。

合法的定义:这个序列中左右括号匹配

题目描述

This is yet another problem dealing with regular bracket sequences.

We should remind you that a bracket sequence is called regular, if by inserting <<+>> and <<1>> into it we can get a correct mathematical expression. For example, sequences <<(())()>>, <<()>> and <<(()(()))>> are regular, while <<)(>>, <<(()>> and <<(()))(>> are not.

You are given a string of <<(>> and <<)>> characters. You are to find its longest substring that is a regular bracket sequence. You are to find the number of such substrings as well.

输入格式

The first line of the input file contains a non-empty string, consisting of <<(>> and <<)>> characters. Its length does not exceed 10\^{6} .

输出格式

Print the length of the longest substring that is a regular bracket sequence, and the number of such substrings. If there are no such substrings, write the only line containing "0 1".

样例 #1

样例输入 #1

复制代码
)((())))(()())

样例输出 #1

复制代码
6 2

样例 #2

样例输入 #2

复制代码
))(

样例输出 #2

复制代码
0 1

考虑这道题的DP方法。

不难想出,要用 f i fi fi 来表示前 i i i 段里面最长的合法括号序列,现在来考虑能够怎么DP。

合法的序列可以有以下两种情况:

  • ((())),也就是单个大括号
  • ()()(()),也就是多个括号

那么对于单个大括号当然就很好维护,他的长度就可以算为最右边的右括号的下表减去最左边的左括号的下表加1,在这种情况下不需要状态转移。

对于多个括号的情况,我们要考虑状态转移。

由于我们在维护段落的合理性的时候是通过栈来维护的,我们用以下变量来实现数组模拟栈stk[N]为栈本身 tt为栈顶,在检测到左括号的时候我们会压入他的下标,那么取出的时候一定是最左边的右括号先去对应最右边的左括号,知道堆中元素全部弹出。

那么我们可以每次检查一下f[stk[tt] - 1]是否有元素,如果有的话就说明了当前右括号对应的左括号的左边是有另一组合理括号段的,那么就加上他。

因为题目要求要记录数量,所以我们使用cnt数组进行各个段落的最长合理子段的数量记录。

那么最终的状态转移方程就是:++cnt[f[i] = i - stk[tt] + 1 + f[stk[tt--] - 1]]


CODE:

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
#define endl '\n'

int stk[N];
int tt = -1;
int f[N];
int cnt[N];

int main(){
    string s;cin >> s;
    for(int i = 0;i < s.size();i++){
        if(s[i] == '(')stk[++tt] = i;
        else if(~tt) ++cnt[f[i] = i - stk[tt] + 1 + f[stk[tt--] - 1]];
    }
    cnt[0] = 1;
    for(int i = s.size();~i;i--){
        if(cnt[i]){
            cout << i << " " << cnt[i] << endl;
            return 0;
        }
    }
    return 0;
}
相关推荐
小羊没烦恼!9 分钟前
Memory 记忆设计讨论:为什么 Agent Memory 不能只靠向量数据库?
java·开发语言·windows·算法·c#
ysu_031443 分钟前
08-二叉树遍历:四种方式详解
c语言·数据结构·算法·leetcode
咸鱼老弟43 分钟前
Speculative Decoding(投机采样):大模型"先猜后验",生成速度翻倍
前端·算法·ai编程
荆棘鸟智能1 小时前
AI算法持续学习与迭代怎么做?从数据闭环到灰度发布的MLOps工程实践
人工智能·算法·架构·边缘计算
Lyyaoo.1 小时前
【二分查找】【中等】搜索二维矩阵/排序数组的第一位和最后位置/搜索旋转排序数组/旋转排序数组中的最小值
java·数据结构·算法
土司大王1 小时前
LeetCode hot100——153.寻找旋转排序数组中的最小值:Java 二分模板与 O(log n) 分析
java·算法·leetcode
光电的一只菜鸡1 小时前
isp中关于锐化对图像清晰度的影响
算法
土司大王2 小时前
LeetCode hot100——4.寻找两个正序数组的中位数:Java 二分第K小 递归裁剪
java·算法·leetcode
薛定e的猫咪2 小时前
(ICML2024)QSM:基于 Q 函数梯度对齐分数场的扩散模型离策略强化学习
人工智能·深度学习·算法
hetao17338372 小时前
2026-09-13 hetao1733837 的刷题记录
c++·算法