Tuesday, April 16, 2019

C. Longest Regular Bracket Sequence

C. Longest Regular Bracket Sequence

Link for the problem:C. Longest Regular Bracket Sequence

Solution:
Every regular bracket sequence can be determined by using a stack.
Let S be the input string and S1 and S2 be the regular bracket substring. 
Then-
1.) '('+S1+')' will be a regular bracket sequence.
2.) S1+S2 will be regular bracket sequence;

CODE:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    string s;
    cin>>s;
    int i,j,k,l;
    int a[1000001]={0};
    l=s.size();
    stack< int> st;
    vector <int> v;
    for(i=0;i<l;i++)
    {
        if(s[i]=='(')
        {
            st.push(i);
        }
        else
        {
            if(st.size()){
            a[i+1]+=-1;
            a[st.top()]+=1;
            st.pop();}
        }
    }
    for(i=1;i<l;i++)
    {
        a[i]=a[i-1]+a[i];
    }
    int sm=0,mx=0;
    for(i=0;i<l;i++)
    {
        if(a[i]>0)
        {
            sm++;
        }
        else
        {
            //printf("Y\n");
            if(sm>mx)
            mx=sm;
            v.push_back(sm);
            sm=0;
        }
    }
    if(sm>mx)
    mx=sm;
    v.push_back(sm);
    l=v.size();
    sm=0;
    for(i=0;i<l;i++)
    {
        if(v[i]==mx)
        {
            sm++;
        }
    }
    if(mx)
    printf("%d %d\n",mx,sm);
    else
    printf("0 1\n");
    return 0;

}

No comments:

Post a Comment

CHEFST: Chef and the stones

CHEFST: Chef and the stones Link for the problem:  CHEFST SOLUTION: For a given max possible no of stones that can be removed from ea...