HDU 5444 Elven Postman (二叉树,暴力搜索)

题意:给出一颗二叉树的先序遍历,默认的中序遍历是1.、2、……n。给出q个询问,询问从根节点出发到某个点的路径。

析:本来以为是要建树的,一想,原来不用,其实它给的数是按顺序给的,只要搜结点就行,从根开始搜,如果要到的结点比根结点大,那么一定是向W走,

然后去第一个结点,然后接着判定,一直走,如果找到结束就好。水题。当时想的有点复杂。

代码如下:

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

using namespace std ;
typedef long long LL;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
const double inf = 0x3f3f3f3f3f3f3f;
const double eps = 1e-8;
const int maxn = 2e5 + 5;
const int dr[] = {0, 0, -1, 1};
const int dc[] = {-1, 1, 0, 0};
int n, m;
inline bool is_in(int r, int c){
    return r >= 0 && r < n && c >= 0 && c < m;
}
int a[maxn];

int main(){
    int T;  cin >> T;
    while(T--){
        scanf("%d", &n);
        for(int i = 0; i < n; ++i){
            scanf("%d", &a[i]);
        }
        scanf("%d", &m);
        while(m--){
            int u;
            scanf("%d", &u);
            int rt = a[0];
            int s = 0;
            while(true){
                if(a[0] == u){    break; }
                if(u > a[s]){
                    printf("W");
                    for(int i = s+1; i < n; ++i){
                        if(a[i] > a[s]){
                            s = i;
                            break;
                        }
                    }
                    if(u == a[s])  break;
                }
                else {
                    printf("E");
                    for(int i = s+1; i < n; ++i){
                        if(a[i] < a[s]){
                            s = i;
                            break;
                        }
                    }
                    if(u == a[s])  break;
                }
            }
            printf("
");
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/dwtfukgv/p/5722137.html