7-1 Is it the same binary search tree (25 points)

A binary search tree can be uniquely determined given an insertion sequence. However, a given binary search tree can be derived from many different insertion sequences. For example, inserting into an initially empty binary search tree according to the sequence {2, 1, 3} and {2, 3, 1} respectively, will get the same result. So for the various insertion sequences of the input, you need to determine whether they can generate the same binary search tree.

Input format:

The input contains several sets of test data. The first row of each set of data gives two positive integers N ( ≤ ) and L, which are the number of elements inserted in each sequence and the number of sequences to be checked, respectively. Line 2 gives N space-separated positive integers as the initial insertion sequence. The last L lines, each giving the N inserted elements, belong to the L sequences that need to be checked.

For simplicity, we guarantee that each insertion sequence is a permutation of 1 to N. When reading N is 0, the input of the flag is over, and this group of data should not be processed.

Output format:

For each set of sequences to be checked, if the binary search tree generated by it is the same as that generated by the corresponding initial sequence, output "Yes", otherwise output "No".

Input sample:

4 2
3 1 4 2
3 4 1 2
3 2 4 1
2 1
2 1
1 2
0

Sample output:

Yes
No
No
代码;

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int n;
void add(int *p,int k,int d)
{
if(p[k] == -1)p[k] = d;
else if(p[k] > d)add(p,k*2,d);
else add(p,k*2+1,d);
}
int comp(int *a,int *b)
{
int c = 0;
for(int i = 0;a[i] == b[i];i ++)
{
if(a[i] != -1)c ++;
if(c == n)break;
}
if(c != n)return 0;
return 1;
}
int main()
{
int a[41],b[41];
int l,d;
while(~scanf("%d",&n)&&n){
scanf("%d",&l);
memset(a,-1,sizeof(a));

for(int i = 0;i < n;i ++)
{
scanf("%d",&d);
add(a,1,d);
}
while(l --)
{
memset(b,-1,sizeof(b));
for(int i = 0;i < n;i ++)
{
scanf("%d",&d);
add(b,1,d);
}
if(comp(a,b))printf("Yes\n");
else printf("No\n");
}
}
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324796035&siteId=291194637