题目描述:
给出一棵n个节点的树,节点编号为1-n(根节点编号为1)。对于每一个叶子节点,输出从根到叶子的路径。(按照路径的字典序)。
输入:
第一行:1个数n(2 < n <= 1000),表示树的节点数量。
后面n-1行:每行2个数x y,表示节点x是节点y的父节点(1 <= x, y <= n)。
输出:
输出行数等于叶子节点的数量,每行对应从根到叶子节点的路径。路径中的数字为经过节点的编号。按照路径的字典序从小到大输出。
数据范围:
对于30%的数据,2 < n <= 10;
对于100%的数据,2 < n <= 1000,1 <= x, y <= n;
样例解释:
3 和 5 为叶子结点,对应的路径分别为1 3和1 2 4 5,后者的字典序更小,因此输出结果为:
1 2 4 5
1 3
思路:
储存每个节点的儿子节点,再从根节点开始dfs,每遇到叶子节点就输出。
代码:
#include <cstdio>
#include <cstring>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <cmath>
#include <algorithm>
#include<bits/stdc++.h>
using namespace std;
const double N = 1e6+10;
const double pi = acos(-1.0);
const int INF = 0x3f3f3f3f;
const int MOD = 1000000007;
const inline int read(){
int k = 0, f = 1; char c = getchar();
for(;!isdigit(c); c = getchar())
if(c == '-') f = -1;
for(;isdigit(c); c = getchar())
k = k * 10 + c - '0';
return k * f;
}
#define ll long long
#define CL(a,b) memset(a,b,sizeof(a))
#define MAXN 100010
long long int b[MAXN];
struct point
{
int deep , size;
vector<int> q;
} a[1010];
int ans[1010];
int o = 1;
void print()
{
for(int i = 1 ; i < o ; i++)
{
cout << ans[i] << " ";
}
cout << ans[o] << endl;
}
void dfs(int id)
{
if(a[id].q.size() == 0)
{
print();
}
for(int i = 0 ; i < a[id].q.size() ; i++)
{
ans[++o] = a[id].q[i];
dfs(a[id].q[i]);
o--;
}
}
int main()
{
int n = read();
for(int i = 1 ; i < n ; i++)
{
int x , y;
x = read();
y = read();
a[x].q.push_back(y);
}
ans[1] = 1;
dfs(1);
return 0;
}