zoukankan      html  css  js  c++  java
  • 【PAT甲级】1127 ZigZagging on a Tree (30分)(已知中序后序蛇形输出层次遍历)

    题意:

    输入一个正整数N(<=30),接着输入两行分别为中序遍历和后序遍历,蛇形输出层次遍历。

    AAAAAccepted code:

     1 #define HAVE_STRUCT_TIMESPEC
     2 #include<bits/stdc++.h>
     3 using namespace std;
     4 typedef struct node{
     5     int num;
     6     int level;
     7     node *lc,*rc;
     8 };
     9 int root;
    10 int in[37],post[37];
    11 int num[37][5];
    12 pair<int,int>ans[37];
    13 void dfs(int &index,int l,int r,int L,int R){
    14     if(l>r)
    15         return ;
    16     int pos=0;
    17     while(in[pos]!=post[R])
    18         ++pos;
    19     index=R;
    20     dfs(num[index][0],l,pos-1,L,L+pos-1-l);
    21     dfs(num[index][1],pos+1,r,L+pos-l,R-1);
    22     return ;
    23 }
    24 int main(){
    25     ios::sync_with_stdio(false);
    26     cin.tie(NULL);
    27     cout.tie(NULL);
    28     int n;
    29     cin>>n;
    30     for(int i=1;i<=n;++i)
    31         cin>>in[i];
    32     for(int i=1;i<=n;++i)
    33         cin>>post[i];
    34     dfs(root,1,n,1,n);
    35     int flag=0;
    36     queue<pair<int,int> >q;
    37     q.push({root,0});
    38     int cnt=0;
    39     while(!q.empty()){
    40         pair<int,int>now=q.front();
    41         q.pop();
    42         ans[++cnt]={post[now.first],now.second};
    43         if(num[now.first][0])
    44             q.push({num[now.first][0],now.second+1});
    45         if(num[now.first][1])
    46             q.push({num[now.first][1],now.second+1});
    47     }
    48     cout<<ans[1].first;
    49     for(int i=2;i<=cnt;++i){
    50         if(ans[i].second&1)
    51             cout<<" "<<ans[i].first;
    52         else{
    53             int pos=cnt;
    54             for(int j=i+1;j<=cnt;++j)
    55                 if(ans[j].second&1){
    56                     pos=j-1;
    57                     break;
    58                 }
    59             for(int j=pos;j>=i;--j)
    60                 cout<<" "<<ans[j].first;
    61             i=pos;
    62         }
    63     }
    64     return 0;
    65 }
  • 相关阅读:
    basis 文档
    profile default1
    profile default
    2101244
    Linux下对lvm逻辑卷分区大小的调整(针对xfs和ext4不同文件系统)
    1816647
    lvm管理:扩展lv、删除pv、lv等
    HPUX and AIX SSH 互信
    SLD Related Gateway Serivces Unavaliable
    [原创]K8 MSF Bind Shell TCP 连接工具
  • 原文地址:https://www.cnblogs.com/ldudxy/p/12516152.html
Copyright © 2011-2022 走看看