hdu5444 (2015 ACM/ICPC Asia Regional Changchun Online)

題面

Elves are very peculiar creatures. As we all know, they can live for a very long time and their magical prowess are not something to be taken lightly. Also, they live on trees. However, there is something about them you may not know. Although delivering stuffs through magical teleportation is extremely convenient (much like emails). They still sometimes prefer other more “traditional” methods.

So, as a elven postman, it is crucial to understand how to deliver the mail to the correct room of the tree. The elven tree always branches into no more than two paths upon intersection, either in the east direction or the west. It coincidentally looks awfully like a binary tree we human computer scientist know. Not only that, when numbering the rooms, they always number the room number from the east-most position to the west. For rooms in the east are usually more preferable and more expensive due to they having the privilege to see the sunrise, which matters a lot in elven culture.

Anyways, the elves usually wrote down all the rooms in a sequence at the root of the tree so that the postman may know how to deliver the mail. The sequence is written as follows, it will go straight to visit the east-most room and write down every room it encountered along the way. After the first room is reached, it will then go to the next unvisited east-most room, writing down every unvisited room on the way as well until all rooms are visited.

Your task is to determine how to reach a certain room given the sequence written on the root.

For instance, the sequence 2, 1, 4, 3 would be written on the root of the following tree.

題意

一個樹中序遍歷是1…n然後給你一個先序遍歷序列,對於每次詢問x,問你走到位置x的行動序列

解法

先序遍歷的特點是左子樹右子樹在後面兩段連續的區間裏,所以只要每次二分一下中間位置,然後遞歸求解子問題就好了。

代碼

#include<bits/stdc++.h>

using namespace std;

typedef long long ll;

const int SIZE = 1005;
int a[SIZE];

void solve(int tg, int now, int r) {
    if(tg == a[now]) return;
    int wst = upper_bound(a + now, a + r, a[now]) - a;
    if(tg > a[now]) {
        printf("W");
        solve(tg, wst, r);
    }
    else {
        printf("E");
        solve(tg, now + 1, wst);
    }
}

int main() {
    int T;
    scanf("%d",&T);
    while(T--) {
        int n;
        scanf("%d",&n);
        for(int i = 0; i < n; i++) scanf("%d",&a[i]);
        int q;
        scanf("%d",&q);
        while(q--) {
            int t;
            scanf("%d",&t);
            solve(t, 0, n);
            puts("");
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章