I need help in this question : https://www.codechef.com/SNCKQL17/problems/SNAKPROC
I used stack to push when ‘H’ is encountered,pop when ‘T’ is encountered and do nothing when ‘.’ is encountered. Since there weren’t any real elements to push or pop, I simply used 1 as a dummy element that would be pushed or popped whenever required. But still I am get WA. Can anyone point out my mistake? Here’s my solution:
#include <iostream>
using namespace std;
int top = -1;
int push(int a[], int x, int n)
{
if(top == n-1)
return 0;
else
{
top += 1;
a[top] = x;
}
return 1;
}
int pop(int a[], int n)
{
if(top == -1)
return 0;
else
{
top--;
}
return 1;
}
int topElement(int a[])
{
return a[top];
}
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int a[n];
string s;
cin>>s;
int len;
len = s.length();
bool flag = true;
for(int i=0;i<len;i++)
{
//char x;
//cin>>x;
if(s[i] == '.')
continue;
else if(s[i] == 'H')
{
if(topElement(a) == 1)
{
flag = false;
//break;
}
else push(a, 1, n);
}
else if(s[i] == 'T')
{
pop(a,n);
if(topElement(a) <= -1)
{
flag = false;
//break;
}
}
}
if(flag == true && topElement(a) != 1)
cout<<"Valid"<<endl;
else cout<<"Invalid"<<endl;
}
return 0;
}