hdu 5444 Elven Postman 2015 长春网络赛 图论 前序中序构建树

本文介绍了一道关于构建树结构并通过深度优先搜索(DFS)遍历解决路径查询问题的算法题。题目要求根据访问节点的顺序构建树,并求解从根节点到指定节点的路径。文章详细解析了解题思路,包括如何利用前序和中序遍历来构建树,以及通过一次DFS遍历得到所有答案的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5444

题目来源:2015 长春网络赛

简要题意:一个人会先走东再走西,点的序号都是东边到西边递增,给你访问到未访问节点的顺序。
     求根到一些点的路径怎么走。

数据范围: T10;n1000;q 

题解

题意非常扭曲,不过读懂之后可以发现就是要用前序和中序去构建树

建好树之后只要从根开始dfs一次就能做出所有的答案了。

实现

根据中序去分段,然后前序建树,最后搜一次。

赛中问学长拿了板直接A。

代码

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <stack>
#include <queue>
#include <string>
#include <vector>
#include <set>
#include <map>

#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define sz(x) ((int)(x).size())
#define fi first
#define se second
using namespace std;
typedef long long LL;
typedef vector<int> VI;
typedef pair<int,int> PII;
LL powmod(LL a,LL b, LL MOD) {LL res=1;a%=MOD;for(;b;b>>=1){if(b&1)res=res*a%MOD;a=a*a%MOD;}return res;}
// head

const int N=1022;

struct Node {
    Node * l;
    Node * r;
    int p;
    Node() {}
    Node (int _p):p(_p) {}
};
int cur=0;

int pre[N],in[N];
string s[N];
int len[N];
Node* build(int l,int r) {
    if (l>r) return 0;
    Node *root=new Node(pre[cur++]);
    for (int i=l; i<=r; i++) {
        if (in[i]==root->p) {
            root->l=build(l,i-1);
            root->r=build(i+1,r);
        }
    }
    return root;
}

void print(Node *root, string ss) {
    if (root==0) return;
    s[root->p] = ss;
    print(root->l, ss+"E");
    print(root->r, ss+"W");
}

int main () {
    int T;
    scanf("%d",&T);
    for (int i=1; i<N; i++)
        in[i]=i;
    while (T--) {
        int n, q, x;
        scanf("%d",&n);
        for (int i=1; i<=n; i++)
            scanf("%d",pre+i);
        cur=1;
        Node *root=build(1,n);
        print(root, "");
        scanf("%d", &q);
        for (int i = 0; i < q; i++) {
            scanf("%d", &x);
            cout << s[x] << endl;
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值