C - Mathematicians and brackets
Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u
Description
Once upon a time three mathematicians met…
- The first of them wrote a sequence of brackets on a chalkboard.
- The second one wondered if there was a cyclic shift turning that sequence into a regular one.
- After thinking for a while, the third mathematician told the number of such shifts.
- An empty string is a regular sequence of brackets.
- If a string a is a regular sequence of brackets, then the string (a) is also a regular sequence of brackets.
- If strings a and b are regular sequences of brackets, then the string ab is also a regular sequence of brackets.
- There are no other regular sequences of brackets.
Input
The only line of the input contains the sequence of brackets written by the first mathematician. The sequence is non-empty and its length doesn't exceed 10
5.
Output
Output the number of cyclic shifts turning the given sequence into a regular one.
Sample Input
input | output |
---|---|
)(() | 1 |
)()( | 2 |
() | 1 |
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
#define MAXN 100010
string input;
int main()
{
int len, t, NumShift, vMin;
cin>>input;
len = input.size();
t = 0;
vMin = MAXN;
for(int i = 0; i < len; i++){
if(input[i] == '(') t++;
else if(input[i] == ')') t--;
if(vMin > t) vMin = t;
}
NumShift = 0;
if(t != 0)
cout<<0<<endl;
else {
for(int i = 0; i < len; i++){
if(input[i] == '(') vMin--;
else if(input[i] == ')') vMin++;
if(vMin >= 0) NumShift++;
}
cout<<NumShift<<endl;
}
return 0;
}