您的位置:首页 > 其它

2017年团体程序设计天梯赛-总决赛 L3-1. 二叉搜索树的结构

2017-04-16 11:15 323 查看
注意一下查询的值不一定都在二叉树上面

#include<bits/stdc++.h>
using namespace std;
int n,t,cnt,f[1024],a,b,fa,fb;
char s[1024];
map<int,int>mp;
struct node
{
int n;
int d;
int l,r;
} p[1024];

void build(int now,int num)
{
if(num<p[now].n)
{
if(p[now].l==-1)
{
p[now].l=cnt;
p[cnt].n=num;
p[cnt].l=p[cnt].r=-1;
cnt++;
}
else build(p[now].l,num);
}
else
{
if(p[now].r==-1)
{
p[now].r=cnt;
p[cnt].n=num;
p[cnt].l=p[cnt].r=-1;
cnt++;
}
else build(p[now].r,num);
}
}

void dfs(int x,int d)
{
mp[p[x].n]=x;
p[x].d=d;
if(p[x].l!=-1)
{
f[p[x].l]=x;
dfs(p[x].l,d+1);
}
if(p[x].r!=-1)
{
f[p[x].r]=x;
dfs(p[x].r,d+1);
}
}

int get()
{
a=b=-1;
int len=strlen(s);
int now=-1,f=1,h1=-1,h2=-1;
for(int i=0; i<len; i++)
{
if(s[i]=='-')
{
f=-1;
}
else if(s[i]>='0'&&s[i]<='9')
{
if(now==-1) now=0;
now=now*10+s[i]-'0';
h2=1;
}
else if(h2!=-1)
{
if(h1==-1) a=f*now;
else b=f*now;
now=-1;
f=1;
h1=1;
h2=-1;
}
}
if(h2!=-1)
{
if(h1==-1) a=f*now;
else b=f*now;
now=-1;
}
for(int i=0; i+2<len; i++)
{
if(s[i]=='r'&&s[i+1]=='o') return 1;
if(s[i]=='s'&&s[i+1]=='i') return 2;
if(s[i]=='p'&&s[i+1]=='a') return 3;
if(s[i]=='e'&&s[i+1]=='f') return 4;
if(s[i]=='r'&&s[i+1]=='i') return 5;
if(s[i]=='s'&&s[i+1]=='a') return 6;
}

}

int main()
{
mp.clear();
cnt=1;
cin>>n;
for(int i=0; i<n; i++)
{
scanf("%d",&t);
if(i==0)
{
p[cnt].n=t;
p[cnt].l=p[cnt].r=-1;
cnt++;
}
else build(1,t);
}
f[1]=-1;
dfs(1,1);
cin>>n;
getchar();
for(int i=0; i<n; i++)
{
gets(s);
int k=get();
int t=0;
fa=mp[a];
fb=mp[b];
//printf("%d %d %d %d\n",a,b,fa,fb);
if(mp[a]==0)
t=0;
else if(k==1)
{
if(f[fa]==-1) t=1;
}
else if(mp[b]==0)
{
t=0;
}
else if(k==2)
{
if(f[fa]==f[fb]) t=1;
}
else if(k==3)
{
if(f[fb]==fa) t=1;
}
else if(k==4)
{
if(p[fb].l==fa) t=1;
}
else if(k==5)
{
if(p[fb].r==fa) t=1;
}
else if(k==6)
{
if(p[fa].d==p[fb].d) t=1;
}
if(t==1) puts("Yes");
else puts("No");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: