Time Limit: 1 Sec, Memory Limit: 128 MB
A bracket sequence is a string,containing only characters "(", ")", "[" and"]". A correct bracket sequence is a bracket sequence that can betransformed into a correct arithmetic expression by inserting characters"1" and "+" between the original characters of thesequence. For example, bracket sequences "()[]", "([])" arecorrect (the resulting expressions are: "(1)+[1]","([1+1]+1)"), and "](" and "[" are not. The emptystring is a correct bracket sequence by definition. A substring s[l... r](1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (where |s| is the length of strings) is the string slsl + 1... sr. The empty string is a substring of any stringby definition. You are given a bracket sequence, not necessarily correct. Findits substring which is a correct bracket sequence and contains as many openingsquare brackets «[» as possible.
Multiple test cases. In the first linethere is an integer T, indicating the number of test cases. For each test case,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 lengthdoesn't exceed 106 characters.
For each case, in the first line printa single integer — the number of brackets «[» in the required bracket sequence.In the second line print the optimal sequence. If there are more than oneoptimal solutions, choose the longest one. If there are still more than onesolutions, choose the one that occurs first.
//看到题目第一反应这应该是数据结构的题目,应该用栈来完成。然而队友告诉我是dp //我觉得这道题的难点在于如何想到这是一道dp题。 //要有敏锐的直觉发现每个步骤之间的关系 //dp[i]:以str[i]结尾的最长合法子串长度 //key[i]:以str[i]结尾的最长合法子串有多少个'[' #include<iostream> #include<cstdio> #include<algorithm> #include<cstring> #include<string> using namespace std; const int N = 2000080; char str[N]; int dp[N], key[N]; int main() { #ifdef glx freopen("in.txt", "r", stdin); #endif int t; cin >> t; while (t--) { memset(dp, 0, sizeof(dp)); memset(key, 0, sizeof(key)); memset(str, 0, sizeof(str)); scanf("%s", str); int len = strlen(str); for (int i = 1; i < len; i++) { int pos = i - dp[i - 1] - 1; if (str[i] == ')') { if (str[pos] == '(') { dp[i] = dp[i - 1] + 2; key[i] = key[i - 1]; if (dp[pos - 1] && pos >= 1) { dp[i] += dp[pos - 1]; key[i] += key[pos - 1]; } } } else if (str[i] == ']') { if (str[pos] == '[') { dp[i] = dp[i - 1] + 2; key[i] = key[i - 1] + 1; if (dp[pos - 1] && pos - 1 > 0) { dp[i] += dp[pos - 1]; key[i] += key[pos - 1]; } } } } int pos = -1, llen = -1, lnum = 0; for (int i = 0; i < len; i++) { if (key[i] > lnum || (dp[i] > llen&&key[i] == lnum)) { pos = i - dp[i] + 1; llen = dp[i]; lnum = key[i]; } } cout << lnum << endl; if (lnum) { for (int i = pos; i < pos + llen; i++) { cout << str[i]; } cout << endl; } } return 0; }