最小DFS序

时间限制:1秒 内存限制:128M

题目描述

一般来讲,我们在对树进行深度优先遍历时,对于每个节点,在刚进入递归后以及即将回溯前各记录一次该节点的编号,最后产生一个长度为2n的节点的序列就称为树的DFS序。

输入描述

第一行,两个整数n(1<=n<=1000),s,其中n表示树的节点的个数,s表示树的根节点的编号。

接下来的n-1行中,每行有两个整数x,y,表示x和y有一条边

输出描述

输出一组字典序最小的DFS序,每两个数字之间用空格隔开。

样例

输入

复制代码
9 1
1 2
1 7
1 4
2 8
2 5
4 6
4 3
3 9

输出

复制代码
1 2 5 5 8 8 2 4 3 9 9 3 6 6 4 7 7 1
cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
const int N=2005;
int head[N],vis[N],ver[N],Next[N],tot=-1,n,S;
struct node{
	int x,y;
}s[2005];
bool cmp(node a,node b){
	if(a.x!=b.x){
		return a.x<b.x;
	}
	return a.y>b.y;
}
void Add(int x,int y){
	ver[++tot]=y;
	Next[tot]=head[x];
	head[x]=tot;
}
void dfs(int pos){
	vis[pos]=1;
	cout<<pos<<" ";
	for(int i=head[pos];i!=-1;i=Next[i]){
		int ljd=ver[i];
		if(vis[ljd]==0){
			dfs(ljd);
		}
	}
	cout<<pos<<" ";
}
int main(){
	cin>>n>>S;
	memset(head,-1,sizeof(head));
	for(int i=1;i<2*n;i+=2){
		cin>>s[i].x>>s[i].y;
		s[i+1].x=s[i].y;
		s[i+1].y=s[i].x;
	}
	sort(s+1,s+2*n-1,cmp);
	for(int i=1;i<2*n;i++){
		Add(s[i].x,s[i].y);
	}
	dfs(S);
	return 0;
} 
相关推荐
小白菜又菜14 小时前
Leetcode 236. Lowest Common Ancestor of a Binary Tree
python·算法·leetcode
不想看见40414 小时前
01 Matrix 基本动态规划:二维--力扣101算法题解笔记
c++·算法·leetcode
多恩Stone14 小时前
【3D-AICG 系列-12】Trellis 2 的 Shape VAE 的设计细节 Sparse Residual Autoencoding Layer
人工智能·python·算法·3d·aigc
踢足球092914 小时前
寒假打卡:2026-2-23
数据结构·算法
田里的水稻15 小时前
FA_建图和定位(ML)-超宽带(UWB)定位
人工智能·算法·数学建模·机器人·自动驾驶
Navigator_Z15 小时前
LeetCode //C - 964. Least Operators to Express Number
c语言·算法·leetcode
郝学胜-神的一滴15 小时前
Effective Modern C++ 条款40:深入理解 Atomic 与 Volatile 的多线程语义
开发语言·c++·学习·算法·设计模式·架构
摸鱼仙人~15 小时前
算法题避坑指南:数组/循环范围的 `+1` 到底什么时候加?
算法
liliangcsdn15 小时前
基于似然比的显著图可解释性方法的探索
人工智能·算法·机器学习
骇城迷影15 小时前
代码随想录:二叉树篇(中)
数据结构·c++·算法·leetcode