-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathparentheses_sequence.cpp
More file actions
113 lines (105 loc) · 2.83 KB
/
parentheses_sequence.cpp
File metadata and controls
113 lines (105 loc) · 2.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <iostream>
#include <vector>
#include <string>
using namespace std;
using ll = long long;
using vvl = vector<vector<ll>>;
using vl = vector<ll>;
class Solution {
public:
ll MO = 1000000007;
pair<int, ll> getRst(string &str) {
int left = 0; // the left side end position
int right = 0; // the right side end position
int len = str.size();
int cur = 0;
int cc = 0;
int left_cc = 0; // the left side missed parentheses
int right_cc = 0; // the right side missed parentheses
int total = 0; // total missed parentheses
// Counting the missed parentheses one the left side or the right side
while (cur < len) {
if (str[cur] == '(') {
++cc;
} else {
--cc;
}
if (cc < 0) {
left = cur;
cc = 0;
++left_cc;
}
if (cc == 0) {
right = cur + 1;
}
++cur;
}
right_cc = cc;
total = left_cc + right_cc;
if (total == 0) {
return pair<int, ll>(0, 1);
}
// Each segment ")....)" view as a component, and when ever we encounter
// the descrease point which '(' less than ')' we need to descrease the
// component element.
vector<ll> dp(left_cc + 1, 0);
dp[0] = 1;
// current component and previous component a least get base element
int base = 1;
cc = 0;
update(dp, base);
for (int i = 0; i < left; ++i) {
if (str[i] == '(') {
++cc;
} else {
--cc;
}
if (cc < 0) {
cc = 0;
++base;
}
if (str[i] == ')') {
update(dp, base);
}
}
ll lm = dp.back();
dp = vector<ll>(right_cc + 1, 0);
dp[0] = 1;
base = 1;
update(dp, base);
cc = 0;
for (int i = len - 1; i > right; --i) {
if (str[i] == ')') {
++cc;
} else {
--cc;
}
if (cc < 0) {
cc = 0;
++base;
}
if (str[i] == '(') {
update(dp, base);
}
}
ll rm = dp.back();
return pair<int, ll>(total, (lm * rm) % MO);
}
// update the dp array
void update(vector<ll> &dp, int base) {
int len = dp.size();
ll acc = dp[base - 1];
for (int i = base; i < len; ++i) {
acc = (acc + dp[i]) % MO;
dp[i] = acc;
}
}
};
int main() {
string str;
cin >> str;
Solution so;
auto rst = so.getRst(str);
cout << rst.first << " " << rst.second << endl;
return 0;
}