HDU 5444 Elven Postman

题意:给一棵二叉树的中序,前序为升序的1~n,m个查询,求从根走到被查询结点的路径。

 

解法:模拟一下给前序中序的建树,边建边记路径就可以了……就是建树的时候写着的有点恶心……

 

代码:

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string>
#include<string.h>
#include<math.h>
#include<limits.h>
#include<time.h>
#include<stdlib.h>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<vector>
#define LL long long
using namespace std;
int a[1005], b[1005];
struct node
{
    int lson, rson;
}p[1005];
string ans[1005];
void dfs(int al, int ar, int bl, int br)
{
    if(al == ar) return ;
    int root = a[al];
    if(b[root] != bl)
    {
        p[root].lson = a[al + 1];
        ans[a[al + 1]] = ans[root] + 'E';
        dfs(al + 1, al + 1 + root - bl - 1, bl, root - 1);
    }
    else p[root].lson = -1;
    if(b[root] != br)
    {
        p[root].rson = a[al + 1 + root - bl];
        ans[a[al + 1 + root - bl]] = ans[root] + 'W';
        dfs(al + 1 + root - bl, ar, root + 1, br);
    }
    else p[root].rson = -1;
}
int main()
{
    for(int i = 1; i <= 1000; i++) b[i] = i;
    int T;
    while(~scanf("%d", &T))
    {
        while(T--)
        {
            for(int i = 1; i <= 1000; i++)
                ans[i].clear();
            int n;
            scanf("%d", &n);
            for(int i = 1; i <= n; i++)
                scanf("%d", &a[i]);
            int root = a[0];
            dfs(1, n, 1, n);
            int m;
            scanf("%d", &m);
            while(m--)
            {
                int x;
                scanf("%d", &x);
                cout << ans[x] << endl;
            }
        }
    }
    return 0;
}

  

posted @ 2015-09-15 13:51  露儿大人  阅读(146)  评论(0编辑  收藏  举报