Snake Procession Problem
The annual snake festival is upon us, and all the snakes of the kingdom have gathered to participate in the procession. Chef has been tasked with reporting on the procession, and for this, he decides to first keep track of all the snakes. When he sees a snake first, it'll be its Head, and hence he will mark an 'H'. The snakes are long, and when he sees the snake finally slither away, he'll mark a 'T' to denote its tail. In the time in between, when the snake is moving past him, or the time between one snake and the next snake, he marks with '.'s.Because the snakes come in a procession, and one by one, a valid report would be something like "..H..T...HTH....T.", or "...", or "HT", whereas "T...H..H.T", "H..T..H", "H..H..T..T" would be invalid reports.
Formally, a snake is represented by an 'H' followed by some (possibly zero) '.'s, and then a 'T'. A valid report is one such that it begins with a (possibly zero-length) string of '.'s, and then some (possibly zero) snakes between which there can be some '.'s, and then finally ends with some (possibly zero) '.'s.
Chef had binged on the festival food and had been very drowsy. So his report might be invalid. You need to help him find out if this report is valid or not.
Input
The first line contains a single integer, R, which denotes the number of reports to be checked. The description of each report follows after this.
The first line of each report contains a single integer, L, the length of that report.
The second line of each report contains a string of length L. The string contains only the characters '.', 'H', and 'T'.
Output
For each report, output the string "Valid" or "Invalid" in a new line, depending on whether it was a valid report or not.
Constraints
1 ≤ R ≤ 500
1 ≤ length of each report ≤ 500
Example
Input:
6
18
..H..T...HTH....T.
3
...
10
H..H..T..T
2
HT
11
.T...H..H.T
7
H..T..H
Output:
Valid
Valid
Invalid
Valid
Invalid
Invalid
Solution:
#include<stdio.h>
#include<string.h>
int main(){
int i,t,l;
scanf("%d",&t);
while(t--){
scanf("%d",&l);
char s[501];
scanf("%s",s);
int l1=strlen(s);
int flag1=10,flag2=10,flag3=10;
int t=0,h=0,f=0,b=0,c=0;
for(i=0;i<l1;i++){
if(s[i]=='H')
b++;
}
for(i=0;i<l1;i++){
if(s[i]=='T')
c++;
}
for(i=0;i<l1;i++){
if(b>c){
printf("Invalid\n");
break;
}
if(s[i]=='H'){
if(flag1==1){
printf("Invalid\n");
break;
}
flag1=1,flag2=0,flag3=0;
h++;
}
if(s[i]=='.'){
flag2=1;
f++;
}
if(s[i]=='T'){
if(flag3==1){
printf("Invalid\n");
break;
}
if(h==0){
printf("Invalid\n");
break;
}
flag3=1,flag2=0,flag1=0;t++;
}
}
if(f+t+h==l1)
printf("Valid\n");
}
return 0;
}
No comments:
Post a Comment