#include<iostream>
using namespace std;
typedef struct Node * Tree;
struct Node {
int Data;
Tree Left, Right;
int flag;
};
Tree NewNode(int tmp)
{
Tree T = new struct Node;
T->Data = tmp;
T->Left = T->Right = NULL;
T->flag = 0;
return T;
}
Tree Insert(Tree T, int tmp)
{
if (!T)
T = NewNode(tmp);
else
{
if (tmp > T->Data)T->Right= Insert(T->Right, tmp);
else if (tmp < T->Data)T->Left= Insert(T->Left, tmp);
}
return T;
}
Tree CreatTree(int N)
{
Tree T;
int tmp;
cin >> tmp;
cin.get();
T = NewNode(tmp);
for (int i = 1; i < N; i++)
{
cin >> tmp;
cin.get();
T = Insert(T, tmp);
}
return T;
}
bool Check(Tree T, int tmp)
{
if (T->flag)
{
if (tmp > T->Data)return Check(T->Right, tmp);
else if (tmp < T->Data)return Check(T->Left, tmp);
else
return false;
}
else
{
if (T->Data == tmp)
{
T->flag = 1;
return true;
}
else
return false;
}
}
bool Judge(Tree T,int N)
{
int tmp;
int flag = 0;
cin >> tmp;
cin.get();
if (T->Data == tmp)T->flag = 1;
else
flag = 1;
for(int i=1;i<N;i++)
{
cin >> tmp;
cin.get();
if (!flag && !Check(T, tmp))flag = 1;
}
if (flag == 1)return false;
else true;
}
void Initialize(Tree T)
{
if (T)
{
T->flag = 0;
Initialize(T->Left);
Initialize(T->Right);
}
}
void FreeTree(Tree T)
{
if (T)
{
FreeTree(T->Left);
FreeTree(T->Right);
delete T;
}
}
int main()
{
while (1)
{
int N, i;
cin >> N;
cin.get();
if (N == 0)break;
int L;
cin >> L;
cin.get();
Tree T = CreatTree(N);
for (i = 0; i < L; i++)
{
Initialize(T);
if (Judge(T, N))cout << "Yes" << endl;
else
cout << "No" << endl;
}
FreeTree(T);
}
return 0;
}
主体思路:建一个树,然后把后面的数进去搜索一下(陈越老师数据结构课上讲的思路,用的这个)
注意,释放空间FreeTree,不然会爆空间不足,递归太占地方,此外,Judge负责输出结果,Check只是一个辅助,之前写的那个版本的Judge和Check运行时间太长了
原来的程序(错误示范,可以运行,但是时间超了)
bool Check(Tree T, int tmp)
{
int flag = 0;
if (T->flag == 0)
{
if (tmp == T->Data)
{
T->flag = 1;
}
else
flag = 1;
}
else
{
if (tmp > T->Data)flag= Check(T->Right, tmp);
else if (tmp < T->Data)flag= Check(T->Left, tmp);
else
flag = 1;
}
return flag;
}
bool Judge(Tree T,int N)
{
int tmp;
while (N--)
{
cin >> tmp;
cin.get();
if(Check(T, tmp))return false;
}
return true;
}