Question link: Click the open link
Question:
Tree of N nodes
1 is root
Then, the leaf node is determined.
The last line shows the order of leaf nodes.
Objectives:
Traverse the tree and output the path. When traversing the leaf node, access the node in the order specified by the leaf node.
Ideas:
Add a priority for each node.
Change the node priority from the last leaf node to the parent node to 1.
Change the vertex priority from the penultimate leaf node to the parent node to 2.
In this way, each vertex has a priority. when accessing a son node, each vertex has a higher priority.
Judgment without solution: the obtained Euler's sequence does not meet the leaf node sequence of input.
#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#include <math.h>#include <set>#include <vector>#include <map>using namespace std;#define ll int#define N 310ll n;vector<ll>G[N];int fa[N], du[N];void dfs(int u,int father){fa[u] = father;for(int i = 0; i < G[u].size(); i++) {int v = G[u][i]; if(v==father)continue;dfs(v,u);}}int val[N], Stack[N<<1], top;bool cmp(int a,int b) {return val[a]>val[b];}void work(int u, int father) {Stack[top++] = u;vector<int>son;son.clear();for(int i = 0; i < G[u].size(); i++){int v = G[u][i]; if(v==father)continue;son.push_back(v);}sort(son.begin(), son.end(), cmp);for(int i = 0; i < son.size(); i++) {work(son[i], u);Stack[top++] = u;}}vector<int>input;bool ok(){int u = 0;for(int i = 0; i < top; i++)if(Stack[i]==input[u])u++;return u >= input.size();}int main(){ll i,j,u,v;while(cin>>n){input.clear();memset(du, 0, sizeof du);for(i = 1; i <= n; i++)G[i].clear();for(i = 1; i < n; i++) {scanf("%d %d",&u,&v);G[u].push_back(v);G[v].push_back(u);du[u]++; du[v]++;}int leaf = 0;for(i = 2; i <= n; i++)if(du[i]==1)leaf++;dfs(1,-1);for(i = leaf; i; i--) {scanf("%d",&u);input.push_back(u);while(u!=-1){val[u] = i;u = fa[u];}}top = 0;work(1,-1);if(ok()) {<span style="white-space:pre"></span>for(i = 0; i < top; i++)printf("%d%c",Stack[i],i==top-1?'\n':' ');}else puts("-1");}return 0;}