#include #include #include #include using namespace std; int rec_children(const vector &v, int index) { int recursive_answer, nc, a; int i; if (v[index] == index+1) return 0; // Base case -- if it's a single node, return 0. nc = 0; recursive_answer = 0; for (i = index+1; i != v[index]; i = v[i]+1) { // Traverse the subtrees nc++; // Use nc to count the number of children. a = rec_children(v, i); // Compute the max children of each subtree. if (a > recursive_answer) recursive_answer = a; } if (nc > recursive_answer) recursive_answer = nc; return recursive_answer; // Return one plus the max children. } int max_children(const string &s) { vector v; deque stack; size_t i, j; v.resize(s.size(), -1); // Create v by using st as a stack for (i = 0; i < s.size(); i++) { if (s[i] == '(') { // Push the index onto the stack on '(' stack.push_front(i); } else { // Otherwise pop the index of the corresponding '(' j = stack[0]; stack.pop_front(); v[j] = i; } } return rec_children(v, 0); // Return the max of children and answers for the children. } int main(int argc, char **argv) { string s; if (argc != 2) { cerr << "usage: a.out string" << endl; exit(1); } s = argv[1]; cout << max_children(s) << endl; return 0; }