(CodeForces - 5C)Longest Regular Bracket Sequence(dp+栈)(最长连续括号模板)
(CodeForces - 5C)Longest Regular Bracket Sequence
time limit per test:2 seconds
memory limit per test:256 megabytes
input:standard input
output:standard output
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.
Input
The first line of the input file contains a non-empty string, consisting of «(» and «)» characters. Its length does not exceed 106.
Output
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”.
Examples
input
)((())))(()())
output
6 2
input
))(
output
0 1
题目意思:
题目的意思就是给你一个小括号的字符串,问你最长的合法括号序列的长度是多少?和有几个这样合法的最长的括号序列
比如:
((())) 这个长度是6,3个左3个右
又比如样例:
)((())))(()())
所以样例的最长长度是6,有两个这样的最长长度的括号段
做法:利用栈进行括号的匹配,加上dp数组记录
dp[i]:位置为i的右括号")"结尾的最长合法括号子序列的长度
dp[i]=dp[temp-1]+i-(temp-1)
其中temp表示与位置为i的右括号匹配的左括号的位置(栈记录了)
code:
#include <iostream> #include <stdio.h> #include<memory> #include<stack> #include<string.h> #include<algorithm> using namespace std; #define max_v 1000005 int dp[max_v];//位置为i的右括号结尾的最长合法括号子序列的长度 //状态转移方程:dp[i]=dp[tmp-1]+i-tmp+1 stack<int> s; int main() { while(!s.empty()) s.pop(); string str; cin>>str; int l=str.size(); int ans=0,sum=0; for(int i=0; i<l; i++) { if(str[i]=='(') s.push(i); else { if(!s.empty()) { int temp=s.top(); s.pop(); if(temp) dp[i]=dp[temp-1]+i-temp+1; else dp[i]=dp[0]+i-temp+1; if(ans<dp[i]) { ans=dp[i]; sum=1; } else if(ans==dp[i]) { sum++; } } } } if(ans==0) { sum=1; } printf("%d %d\n",ans,sum); return 0; } /* 题目意思很简单,就是给以一串括号,要求最长合法括号子序列。 这是典型的括号题,括号题一般都可以用栈+dp解决。 设dp[i]表示位置为i的右括号结尾的最长合法括号子序列的长度,则易得: dp[i]=dp[tmp-1]+i-tmp+1,其中tmp表示与位置为i的右括号匹配的左括号的位置(可以用栈记录)。 */
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南