题目
题意: 给定n个互不相同的整数(可能为负数,题目处处有坑),要求按照输入顺序插入一棵初始为空的二叉搜索树。之后有6种判断,分别是判断根、siblings、左儿子、右儿子、是否同层的关系。
思路: 可以真的建一颗树,但是也可以只用map维护相关信息进行建树,参考了一战南大大佬的code,tql.
时间复杂度: O(nlogn + mnlogn) = O(能过)
代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<complex>
#include<cstring>
#include<cmath>
#include<vector>
#include<map>
#include<unordered_map>
#include<list>
#include<set>
#include<queue>
#include<stack>
#define OldTomato ios::sync_with_stdio(false),cin.tie(nullptr),cout.tie(nullptr)
#define fir(i,a,b) for(int i=a;i<=b;++i)
#define mem(a,x) memset(a,x,sizeof(a))
#define p_ priority_queue
// round() 四舍五入 ceil() 向上取整 floor() 向下取整
// lower_bound(a.begin(),a.end(),tmp,greater<ll>()) 第一个小于等于的
// #define int long long //QAQ
using namespace std;
typedef complex<double> CP;
typedef pair<int,int> PII;
typedef long long ll;
// typedef __int128 it;
const double pi = acos(-1.0);
const int INF = 1<<30;
const ll inf = 1e18;
const int N = 2e5+10;
const int M = 1e6+10;
const int mod = 1e9+7;
const double eps = 1e-6;
inline int lowbit(int x){ return x&(-x);}
template<typename T>void write(T x)
{
if(x<0)
{
putchar('-');
x=-x;
}
if(x>9)
{
write(x/10);
}
putchar(x%10+'0');
}
template<typename T> void read(T &x)
{
x = 0;char ch = getchar();ll f = 1;
while(!isdigit(ch)){if(ch == '-')f*=-1;ch=getchar();}
while(isdigit(ch)){x = x*10+ch-48;ch=getchar();}x*=f;
}
int n,m,k,T;
int root;
map<int,int> mp,l,r;
int a[102];
bool flag;
void insert(int &x,int &root,int cnt)
{
if(root == INF)
{
root = x; mp[x] = cnt;
return ;
}
if(x < root)
{
insert(x,l[root],cnt+1);
}
if(x > root)
{
insert(x,r[root],cnt+1);
}
}
void solve1(int &x,int &y,string &s)
{
cin>>s>>s;
if(s == "root")
{
if(x == root) flag = true;
}
else
{
if(s == "parent")
{
cin>>s>>y;
if(l[x] == y || r[x] == y) flag = true;
}
else
{
if(s == "left")
{
cin>>s>>s>>y;
if(l[y] == x) flag = true;
}
else
{
cin>>s>>s>>y;
if(r[y] == x) flag = true;
}
}
}
}
void solve2(int &x,int &y,string &s)
{
cin>>y>>s>>s;
if(s == "siblings")
{
if(x > y) swap(x,y);
for(int i=0;i<n;++i)
{
if(l[a[i]] == x && r[a[i]] == y) flag = true;
}
}
else
{
cin>>s>>s>>s;
if(mp[x] && mp[x] == mp[y]) flag = true;
}
}
void solve()
{
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
cin>>n;
for(int i=0;i<n;++i) cin>>a[i],l[a[i]] = r[a[i]] = INF; root = a[0]; mp[root] = 1;
for(int i=1;i<n;++i) insert(a[i],root,1);
cin>>m;
while(m--)
{
int x,y;string s;
cin>>x>>s;
flag = false;
if(s == "is") solve1(x,y,s);
else solve2(x,y,s);
if(flag) cout<<"Yes\n";
else cout<<"No\n";
}
}
signed main(void)
{
T = 1;
// OldTomato; cin>>T;
// read(T);
while(T--)
{
solve();
}
return 0;
}