hdu5444

来源:互联网 发布:activity之间数据传递 编辑:程序博客网 时间:2024/05/22 13:19

题目链接:hdu5444


题目大意:按题目意思给出某棵树的访问序列,第一个数为根节点,后一个数如果小于等于根节点则为根节点的右孩子,否则为左孩子,然后在以孩子为根节点按以上规律建树。现在有q个询问,求从根节点出发访问某个节点的路径,如果访问的为左孩子输出‘W’,右孩子输出‘E’。


题目分析:数据量很小,按照题目要求建树,输出节点的访问路径即可。(ps:代码参考自大神队友点击打开链接)


代码:

#include <queue>#include <stdio.h>#include <string.h>#include <iostream>#include <algorithm>using namespace std;typedef long long LL;const int maxn=2000;int T,n,q,tot,value;struct Tree{    int l,r,val;}tree[maxn];void init(int x){    tree[tot].val=0;    tree[tot].l=tree[tot].r=-1;}void build(int value){    int u=0;    while(true)    {        if(value<=tree[u].val){            if(tree[u].r==-1){                tot++;                init(tot);                tree[u].r=tot;                tree[tot].val=value;                return;            } else {                u=tree[u].r;            }        } else {            if(tree[u].l==-1){                tot++;                init(tot);                tree[u].l=tot;                tree[tot].val=value;                return;            } else {                u=tree[u].l;            }        }    }}void query(int value){    int u=0;    while(tree)    {        if(value==tree[u].val){            cout<<endl;            return;        } else if(value<tree[u].val){            cout<<"E";            u=tree[u].r;        } else {            cout<<"W";            u=tree[u].l;        }    }}int main(){//    freopen("in.txt","r",stdin);//    freopen("out.txt","w",stdout);    ios::sync_with_stdio(false);    cin>>T;    while(T--)    {        tot=0;        cin>>n;        for(int i=1;i<=n;i++){            cin>>value;            if(i==1){                init(tot);                tree[tot].val=value;                continue;            }            build(value);        }        cin>>q;        while(q--)        {            cin>>value;            query(value);        }    }    return 0;}


原创粉丝点击