-
Description:
-
Can you find the longest legal sequence of parentheses in a sequence of N consisting of '(' and? The meaning of a valid sequence of parentheses is that in this sequence, all the left Brackets have a unique right brace match, and all the right Brackets have a unique left brace match. For example: () is a legal sequence of parentheses with a length of 10, and () (is not. What you need to solve is to find the longest length of the Legal parentheses subsequence and the number of sequences with such length.
-
Input:
-
There are multiple test data. Each test data contains two rows: the first row is an integer of n, where n cannot exceed 10 ^ 6. The second behavior is a string with a length of N, which consists of the left brace '(' and right brances.
-
Output:
-
For each test case, a line is output, which contains two integers, representing the length and number of the longest legal parentheses sequence, separated by spaces. If no valid sub-sequence exists, 0 1 is returned.
-
Sample input:
-
6(())()3))(
-
Sample output:
-
6 10 1
A bool array is used to mark matching conditions.
1 #include <iostream> 2 #include <stack> 3 #include <string> 4 #include <cstring> 5 using namespace std; 6 7 int n; 8 string s; 9 10 void getRes() {11 bool a[s.length()];12 memset(a, false, s.length());13 stack<int> st;14 for (int i = 0; i < s.length(); ++i) {15 if (s[i] == ‘(‘) {16 st.push(i);17 } else {18 if (!st.empty()) {19 a[i] = true;20 a[st.top()] = true;21 st.pop();22 }23 }24 }25 26 int max = 0, cnt = 1, tmp = 0;27 for (int i = 0; i < s.length(); ++i) {28 if (a[i]) {29 ++tmp;30 } else {31 tmp = 0;32 }33 if (max == tmp && max != 0) {34 ++cnt;35 } else if (max < tmp) {36 max = tmp;37 cnt = 1;38 }39 }40 cout << max << " " << cnt << endl;41 }42 43 int main() {44 while (cin >> n) {45 cin >> s;46 getRes();47 }48 return 0;49 }50 51 /**************************************************************52 Problem: 133753 User: hupo25054 Language: C++55 Result: Accepted56 Time:310 ms57 Memory:7604 kb58 ****************************************************************/