【CodeForces】223A - Bracket Sequence(栈 & 模拟)

来源:互联网 发布:windows自带远程协助 编辑:程序博客网 时间:2024/06/05 22:58

点击打开题目

A. Bracket Sequence
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

bracket sequence is a string, containing only characters "(", ")", "[" and "]".

correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([])" are correct (the resulting expressions are: "(1)+[1]", "([1+1]+1)"), and "](" and "[" are not. The empty string is a correct bracket sequence by definition.

substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (where |s| is the length of string s) is the string slsl + 1... srThe empty string is a substring of any string by definition.

You are given a bracket sequence, not necessarily correct. Find its substring which is a correct bracket sequence and contains as many opening square brackets «[» as possible.

Input

The first and the only line contains the bracket sequence as a string, consisting only of characters "(", ")", "[" and "]". It is guaranteed that the string is non-empty and its length doesn't exceed 105 characters.

Output

In the first line print a single integer — the number of brackets «[» in the required bracket sequence. In the second line print the optimal sequence. If there are more than one optimal solutions print any of them.

Examples
input
([])
output
1([])
input
(((
output
0


这道题做起来好烦啊,说一下思路吧:

像平时括号配对问题一样,能配对的弹出,否则就压入栈(下标),最后得到的栈两两数中间是能配对的(不包括开头结尾),然后依次取数算次数就行了。


代码如下:

#include <cstdio>#include <map>#include <stack>#include <cstring>#include <algorithm>using namespace std;int main(){map<char,int> m;m['('] = 1;m[')'] = -1;m['['] = 2;m[']'] = -2;char str[100000+22];int l;int ans;while (~scanf ("%s",str)){l = strlen(str);stack<int> s;ans = 0;for (int i = 0 ; i < l ; i++){if (m[str[i]] == 1 || m[str[i]] == 2)s.push(i);else if (s.empty())s.push(i);else if (m[str[i]] + m[str[s.top()]] == 0)//可以配对,弹出s.pop();else//不能配对,压入 s.push(i);}if (s.empty())//全部完成匹配 {for (int i = 0 ; i < l ; i++)if (m[str[i]] == 2)ans++;printf ("%d\n%s\n",ans,str);}else{int st,endd;int ans_st,ans_endd;//满足条件的开始于结束位置int ant;s.push(l);while (s.size() != 1){endd = s.top() - 1;s.pop();st = s.top() + 1;ant = 0;for (int i = st ; i <= endd ; i++)if (m[str[i]] == 2)ant++;if (ant > ans){ans = ant;ans_st = st;ans_endd = endd;}}st = 0;endd = s.top() - 1;ant = 0;for (int i = st ; i <= endd ; i++)if (m[str[i]] == 2)ant++;if (ant > ans){ans = ant;ans_st = st;ans_endd = endd;}if (ans){printf ("%d\n",ans);for (int i = ans_st ; i <= ans_endd ; i++)printf ("%c",str[i]);printf ("\n");}elseprintf ("0\n\n");}}return 0;} 


0 0
原创粉丝点击