题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=5444
题意:
给你n个数字,这n个数字是按照二叉搜索树的节点特性给你的,让你建好这棵二叉搜索树,然后,再给出一些询问,让你回答从根节点到某个节点该怎么走?
http://www.cnblogs.com/zyf0163/p/4805218.html?tvd 样例解释的题意
题解:
dfs: http://www.cnblogs.com/qscqesze/p/4805305.html Orz 居然可以这样写
树的形态是唯一的
我们可以处理每个节点能够放的点的大小的范围,然后就可以求出这棵树的样子了
回答就可以顺便再DFS建树的过程中处理出来
建树:http://www.cnblogs.com/wikioibai/p/4810534.html
按照左子树<根节点<右子树的方式来建树,然后再根据这种方式从根节点开始查询就可以了。
代码:
代码一: dfs
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define MS(a) memset(a,0,sizeof(a))
#define MP make_pair
#define PB push_back
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
inline ll read(){
ll x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
//////////////////////////////////////////////////////////////////////////
const int maxn = 1e5+10;
int p[maxn];
int n,ctt;
vector<int> qq;
struct node{
string str;
int L,R;
}c[maxn];
int dfs(int u){
if(ctt == n+1) return true;
while(1){
if(c[u].L<=p[ctt] && p[ctt]<=c[u].R){
int x = p[ctt];
int y = u;
if(x < y){
c[x].str = c[u].str + "E";
c[x].L = c[u].L;
c[x].R = y;
}else{
c[x].str = c[u].str + "W";
c[x].L = y;
c[x].R = c[u].R;
}
ctt++;
if(ctt == n+1) return true;
if(dfs(x)) return true;
}else
return false;
if(ctt == n+1) return true;
}
}
int main(){
int T=read();
while(T--){
qq.clear();
n = read();
for(int i=1; i<=n; i++){
p[i] = read();
}
int q = read();
for(int i=1; i<=q; i++){
int x = read();
qq.push_back(x);
}
for(int i=1; i<=n; i++){
c[i].str = "";
c[i].L=-10000,c[i].R=10000;
}
ctt = 2;
dfs(p[1]);
for(int i=0; i<(int)qq.size(); i++)
cout << c[qq[i]].str << endl;
}
return 0;
}
代码二:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define MS(a) memset(a,0,sizeof(a))
#define MP make_pair
#define PB push_back
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
inline ll read(){
ll x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
//////////////////////////////////////////////////////////////////////////
const int maxn = 1e5+10;
struct Node{
int val;
int child[2];
Node(int k=0){
this->val = k;
MS(child);
}
};
struct Tree{
Node node[maxn];
int sz;
void init(){
sz = 0;
}
int newnode(int x){
node[++sz] = Node(x);
return sz;
}
void insert(int &u, int x){ // 引用真是妙
if(u == 0){
u = newnode(x);
return ;
}
if(node[u].val > x){
insert(node[u].child[0],x);
}else{
insert(node[u].child[1],x);
}
}
void find(int u,int x){
if(u == 0){
return ;
}
if(node[u].val > x){
printf("E");
find(node[u].child[0],x);
}else if(node[u].val < x){
printf("W");
find(node[u].child[1],x);
}
}
}tree;
int main(){
int T=read();
while(T--){
int n = read();
int root = 0;
tree.init();
for(int i=1; i<=n; i++){
int x = read();
tree.insert(root,x);
}
int q = read();
while(q--){
// cout << "rr " << root << endl;
int x=read();
tree.find(root,x);
puts("");
}
}
}