惯例,扔题,懒得说
http://codeforces.com/problemset/problem/5/C?csrf_token=4667d873144028a7886b354c7aae3373
贪心算法比较直接,也比较简单,按照题目要求直接写就好,主要就考虑DP
这个题很有意思的一点是利用了括号的匹配性以及该性质与栈的相性,利用栈来记录位置坐标实现DP,这在日后的编程工作中是一个可以拿来尝试的应用。
同时,在提交的过程中发现的那个错误,需要注意数组的长度,确定下表的长度不越界
在具体的DP中,用栈来依次记录序列中的左括号位置,每当出现一个右括号,判断栈是否为空,若不为空,用此时右括号的位置i减去最近的左括号位置再+1即可得到串的长度。
但是由于我们最后需要的是最长的子串,所以我们可以设dp[i]表示到第i个右括号所获串的长度,t表示离i最近的那个左括号的位置
则dp[i]=dp[t-1]+i-t+1。
最后利用判断语句更新dp[i]代表的字串长度。
最后,补几个有遗忘关于栈的知识点:
std::stack::top | 返回 stack 中顶元素的引用 |
std::stack::pop | 删除栈顶元素 |
std::stack::empty | 判断栈是否为空,为空则返回true |
最后是代码,写代码实在是懒得切换输入法,索性以后用英语写注释好了
#include<bits/stdc++.h>
using namespace std;
const int maxn=1000005;
char s[maxn];
int dp[maxn];
stack<int>pos;//using the stack to record the position of left bracket
int main()
{
while(scanf("%s",s+1)!=EOF)
{
int cnt=0,ans=0;//cnt means the count of string;ans means the length of string
int l=strlen(s+1);
for(int i=1;i<=l;i++)
{
if(s[i]=='(')
{
pos.push(i);
}
else
{
if(!pos.empty())
{
int t=pos.top();
pos.pop();
dp[i]=dp[t-1]+i-t+1;
if(dp[i]>ans)
{
ans=dp[i];
cnt=1;
}
else if(dp[i]==ans)
{
cnt++;
}
}
}
}
if(!ans)
{
cnt=1;
}
printf("%d %d\n",ans,cnt);
}
return 0;
}
参考引用
https://zh.cppreference.com/w/cpp/container/stack/
https://blog.youkuaiyun.com/u014679804/article/details/44873365
https://blog.youkuaiyun.com/qq_38538733/article/details/77091811