Q-Sequence
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)
Total Submission(s): 54 Accepted Submission(s): 6
Problem Description
A Q-sequence is defined as:
Q-Seq := 0 or
Q-Seq := Q-seq Q-seq 1
That is to say a Q-Sequence is a single '0' or two Q-Sequences followed by an '1'.
Given a sequence of '0's and '1's, you are to determine whether it is a Q-Sequence.
Input
The first line is a number n refers to the number of test cases. Then n lines follows, each line has a string made up of '1's and '0's. The maximum length of the sequence is 1000.
Output
The output contain n lines, print "Yes" if it is a Q-sequence, otherwise print "No".
Sample Input
3
0010011
0101
00011
Sample Output
Yes
No
Yes
Author
Agreal@TJU
#include<iostream>
#include<cstring>
using namespace std;
char * sub_string(char *s,int first_index,int last_index)
{
int len=strlen(s);
char *sub=new char[len];
for( int i=0;i<last_index-first_index;i++ )
sub[i]=s[first_index+i];
return sub;
}
bool is_QS(char s[])
{
int len=strlen(s);
if( len==1 && s[0]=='0' )
return true;
else if(s[len-1]=='1')
{
//i---1~len-2
for(int i=1;i<=len-2;i++)
{
char *sub1=new char[i];
char *sub2=new char[len-1-i];
sub1=sub_string(s,len-1-i,len-1-1);//最好动态份配
sub2=sub_string(s,0,len-1-i-1);
if( is_QS(sub1) && is_QS(sub2))
{
delete sub1,sub2;
return true;
}
else
{ delete sub1,sub2;
return false;
}
}
}
else
return false;
}
int main()
{ char s[1001];
cin>>s;
//int len=strlen(s);
// cout<<s<<" "<<endl;
if( is_QS(s) )
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
return 0;
}