zoukankan      html  css  js  c++  java
  • 1127 ZigZagging on a Tree (30 分)

    水~,基于层序遍历。

    树高最坏情况下为(n),即为一条链。

    const int N=35;
    unordered_map<int,int> pos;
    unordered_map<int,PII> tree;
    unordered_map<int,int> dep;
    int in[N],post[N];
    int n;
    vector<int> level[N];
    int maxh;
    
    int build(int inl,int inr,int postl,int postr)
    {
        if(inl > inr) return -1;
    
        int root=post[postr];
        int k=pos[root];
        int leftLen=k-inl;
        int lchild=build(inl,k-1,postl,postl+leftLen-1);
        int rchild=build(k+1,inr,postl+leftLen,postr-1);
        tree[root]={lchild,rchild};
        return root;
    }
    
    void bfs(int root)
    {
        queue<int> q;
        q.push(root);
        dep[root]=1;
        while(q.size())
        {
            int t=q.front();
            q.pop();
    
            maxh=max(maxh,dep[t]);
            level[dep[t]].pb(t);
    
            if(~tree[t].fi)
            {
                dep[tree[t].fi]=dep[t]+1;
                q.push(tree[t].fi);
            }
            if(~tree[t].se)
            {
                dep[tree[t].se]=dep[t]+1;
                q.push(tree[t].se);
            }
        }
    }
    
    int main()
    {
        cin>>n;
    
        for(int i=0;i<n;i++) cin>>in[i],pos[in[i]]=i;
        for(int i=0;i<n;i++) cin>>post[i];
    
        int root=build(0,n-1,0,n-1);
    
        bfs(root);
    
        for(int i=1;i<=maxh;i++)
        {
            if(i & 1) reverse(level[i].begin(),level[i].end());
    
            for(int j=0;j<level[i].size();j++)
                if(j) cout<<' '<<level[i][j];
                else cout<<level[i][j];
    
            if(i<maxh) cout<<' ';
            else cout<<endl;
        }
        //system("pause");
        return 0;
    }
    
  • 相关阅读:
    Xcode及模拟器SDK下载
    修改Navigation Bar上的返回按钮文本颜色,箭头颜色以及导航栏按钮的颜色
    NJKWebViewProgress ——webview进度条
    _tmain 和 main
    XSS原理
    逆向工程
    guide
    网络数据包
    Linux 文件系统 和文件属性
    Linux 文件系统
  • 原文地址:https://www.cnblogs.com/fxh0707/p/14521950.html
Copyright © 2011-2022 走看看