BIT2014级软件学院程序设计-21括号序列

来源:互联网 发布:淘宝网药店购药 编辑:程序博客网 时间:2024/05/18 12:03

题目描述:

一个括号序列是指一个由'(', ')', '[', ']'四种字符组成的字符串。

一个只包含数字,加号'+',和上述四种括号的合法算数表达式,去掉数字和加号之后得到的括号序列成为合法的括号序列。我们定义空串也是合法的括号序列。

例如(1) + [2], ([3]), 4 + [5]相应的括号序列 "()[]", "([])", "[]"都是合法的括号序列。而(6 + 7], [8 + ((9对应的"(]", "[(("则是非法的。

字符串s0s1s2⋯s|s|−1的子串s[l,r](0≤ l≤r<|s|)是指slsl+1⋯sr。

现在给定一个括号序列,请找出其中的一个子串,使得这个子串是合法的括号序列,且包含的'['数量最多。

 

输入:

一个括号序列s。1≤|s|≤5×100000

 

输出:

第一行,答案要求的子串中包含'['的数量。

如果答案是0,输出到此为止,否则:

第二行,两个整数l, r。表示子串第一个字符的位置和最后一个字符的位置。

如果有多个满足条件的字符串,请输出使得子串长度最大的答案。如果长度最大的仍有多个,请输出r最大的。

 

样例:

input:

([])

output:

1

0 3

 用栈的思想。先入后出。用一个数组来模拟栈。然后就是一些细节的处理。

#pragma comment(linker, "/STACK:102400000,102400000")#include<stdio.h>#include<string.h>#include<stdlib.h>#define maxn 500005char ch[maxn];typedef struct {int pos;char cc;}NODE;NODE stack[maxn];typedef struct {int left, right, leng;}ANS;ANS ans;int top=0;int l, r, le;void push(int k, char c){top++;stack[top].pos = k;stack[top].cc = c;}void pull(int k,char c){if (top > 0){if (stack[top].cc != c){top = 0;l = maxn;r = 0;le = 0;}else {if (stack[top].pos < l)l = stack[top].pos;r = k;if (c == '[')le++;top--;if( (le > ans.leng || (le == ans.leng&&r - l > ans.right - ans.left))&&stack[top].pos<=l){ans.left = l;ans.leng = le; ans.right = r;}}}else {top = 0;l = maxn;r = 0;le = 0;}}void pull1(int k,char c){if (top > 0){if (stack[top].cc != c){top = 0;l = 0;r = 0;le = 0;}else {if (stack[top].pos > r)r = stack[top].pos;l = k;if (c == ']')le++;top--;if( (le > ans.leng || (le == ans.leng&&r - l > ans.right - ans.left))&&stack[top].pos>=r&&stack[top].pos>=r){ans.left = l;ans.leng = le; ans.right = r;}}}else {top = 0;l = maxn;r = 0;le = 0;}}int main(){//freopen("E:in.txt","r",stdin);//freopen("E:outt.txt","w",stdout);int i;int len;while(scanf("%s", ch)!=EOF){len = strlen(ch);ans.left = maxn;ans.right = 0;ans.leng = 0;top=0;l=maxn;r=0;le=0;stack[0].pos=maxn;for (i = len-1;i >= 0;i--){if (ch[i] == ']'||ch[i]==')'){push(i,ch[i]);} if (ch[i] == '['){pull1(i,']');}if (ch[i] == '(')pull1(i, ')');}l=maxn;r=0;le=0;top=0;stack[0].pos=0;for (i = 0;i < len;i++){if (ch[i] == '['||ch[i]=='('){push(i,ch[i]);} if (ch[i] == ']'){pull(i,'[');}if (ch[i] == ')')pull(i, '(');}printf("%d\n", ans.leng);if (ans.leng)printf("%d %d\n", ans.left, ans.right);}}

0 0
原创粉丝点击