题目
题意: RT.
思路: 用指针写,C++的指针还比C语言好写一点。这个是通用写法,如果权值各不相同直接用map维护就好了。
时间复杂度: O(n)
代码:
#include<bits/stdc++.h>
using namespace std;
int n,m,k,T;
const int N = 1e5+10;
struct node{
int x;
node*l;
node*r;
};
node* newnode(int x)
{
node *tmp = new node;
tmp->x = x;
tmp->l = NULL;
tmp->r = NULL;
return tmp;
}
int in[N];
int pre[N];
node* get(int l1,int r1,int l2,int r2)
{
if(l1 > r1) return NULL;
int idx;
for(int i=l1;i<=r1;++i) if(in[i] == pre[l2]) idx = i;
node*root = newnode(pre[l2]);
int len = idx-l1;
root->l = get(l1,idx-1,l2+1,l2+len);
root->r = get(idx+1,r1,l2+len+1,r2);
return root;
}
void bfs(node*root)
{
queue<node*> q;
q.push(root);
// vector<int> va;
while(q.size())
{
node*tmp = q.front(); q.pop();
if(tmp == root)
{
cout<<tmp->x;
}
else cout<<" "<<tmp->x;
if(tmp->r != NULL) q.push(tmp->r);
if(tmp->l != NULL) q.push(tmp->l);
}
}
void solve()
{
cin>>n;
for(int i=1;i<=n;++i) cin>>in[i];
for(int i=1;i<=n;++i) cin>>pre[i];
node *root = get(1,n,1,n);
bfs(root);
}
signed main(void)
{
solve();
return 0;
}