这道题需要首先建立一个二叉搜索树,然后再一一对比。
#include<bits/stdc++.h>
#define fi first
#define se second
#define pb pusb_back
#define SZ(x) (ll)x.size()
#define rep(i,a,b) for(ll i=(a);i<=(b);++i)
#define per(i,a,b) for(ll i=(a);i>=(b);--i)
#define mem(a,b) memset(a,b,sizeof a)
using namespace std;
typedef long long ll;
typedef vector<ll> vi;
typedef pair<int,int> pii;
typedef struct Node *node;
template<class T>
inline void read(T &x) {
x=0;
ll f=0;
char c=getchar();
while(!isdigit(c)) {
f|=(c=='-');
c=getchar();
}
while(isdigit(c)) {
x=(x<<3)+(x<<1)+c-'0';
c=getchar();
}
if(f) x=-x;
}
const int maxn=1e2+5,inf=0x3f3f3f3f;
ll vis[maxn];
struct Node {//建立一个结构体存储节点的值和左右子树。
ll val;
node lf,rf;
};
node create(node t,ll x) {
if(t==nullptr) {
t=new Node({x,nullptr,nullptr});
} else if(x<t->val)
t->lf=create(t->lf,x);
else
t->rf=create(t->rf,x);
return t;
}
bool check(node t,ll x) {
if(!vis[t->val] && x!=t->val)
return false;
vis[t->val]=1;
if(x==t->val)
return true;
if(x<t->val)
return check(t->lf,x);
else
return check(t->rf,x);
}
int main() {
ll n,m,x;
while(cin >> n && n) {
cin>>m;
node t=nullptr;
rep(i,1,n) {
cin >> x;
t=create(t,x);
}
while(m--) {
ll f=1;
mem(vis,0);
rep(j,1,n) {
cin >> x;
if(!check(t,x))
f=0;
}
if(f)
puts("Yes");
else
puts("No");
}
}
return 0;
}
建立二叉搜索树的模板:
node create(node t,ll x) {
if(t==nullptr) {
t=new Node({x,nullptr,nullptr});
} else if(x<t->val)
t->lf=create(t->lf,x);
else
t->rf=create(t->rf,x);
return t;
}