1053 Path of Equal Weight (30分)
Given a non-empty tree with root R, and with weight W**i assigned to each tree node T**i. The **weight of a path from **R to L is defined to be the sum of the weights of all the nodes along the path from R to any leaf node L.
Now given any weighted tree, you are supposed to find all the paths with their weights equal to a given number. For example, let’s consider the tree showed in the following figure: for each node, the upper number is the node ID which is a two-digit number, and the lower number is the weight of that node. Suppose that the given number is 24, then there exists 4 different paths which have the same given weight: {10 5 2 7}, {10 4 10}, {10 3 3 6 2} and {10 3 3 6 2}, which correspond to the red edges in the figure.
Input Specification:
Each input file contains one test case. Each case starts with a line containing 0<N≤100, the number of nodes in a tree, M (<N), the number of non-leaf nodes, and 0<S<230, the given weight number. The next line contains N positive numbers where W**i (<1000) corresponds to the tree node T**i. Then M lines follow, each in the format:
ID K ID[1] ID[2] ... ID[K]
where ID
is a two-digit number representing a given non-leaf node, K
is the number of its children, followed by a sequence of two-digit ID
's of its children. For the sake of simplicity, let us fix the root ID to be 00
.
Output Specification:
For each test case, print all the paths with weight S in non-increasing order. Each path occupies a line with printed weights from the root to the leaf in order. All the numbers must be separated by a space with no extra space at the end of the line.
Note: sequence {A1,A2,⋯,A**n} is said to be greater than sequence {B1,B2,⋯,B**m} if there exists 1≤k<min{n,m} such that A**i=B**i for i=1,⋯,k, and A**k+1>B**k+1.
Sample Input:
20 9 24
10 2 4 3 5 10 2 18 9 7 2 2 1 3 12 1 8 6 2 2
00 4 01 02 03 04
02 1 05
04 2 06 07
03 3 11 12 13
06 1 09
07 2 08 10
16 1 15
13 3 14 16 17
17 2 18 19
Sample Output:
10 5 2 7
10 4 10
10 3 3 6 2
10 3 3 6 2
题目大意:
给定一个带权的多叉树,规定从从根节点出发,到叶子节点算做是一条路径。现在给定一个权值,让我们从这个多叉树中找出所有的路径组合,每一条路径上权值之和都等于给定的这个权值。 最后输入每一条路径,并且需要对路径进行排序。排序的规则是:对于同一个下标位置,如果A[i] >B[i]那么路径A 就是比路径B 要大
思路分析:
碰到路径问题,一般都是可以用深度优先遍历和广度优先遍历进行路径搜索。本题中,我直接按照图进行处理,因为树也是一种图。因此,我使用二维数组存储这个树结构。然后在二维数组中进行深度优先遍历。
问题1:什么时候我们是访问到一个叶子节点了呢? 我们知道,当从根节点开始进行深度优先遍历, 当访问到了一个叶子节点,说明我们在此时找到了一条从根节点 到叶子节点的路径。 此时也是进行下一步操作,然后递归返回的时候。其实判断一个节点是不是叶子节点比较容易的做法的在读取数据的时候,用一个boolean数组直接把非叶子节点所在的位置标记为 true,剩下的节点就都是叶子节点。所有节点的编号都是从0 开始连续编号,比如说有 8 个节点,那么编号就是0-7. 因为从输入的第三行开始,每一行的第一个数据就是非叶子节点的编号index,因此在读入数据的时候,boolean 数组对应的位置直接标记为true即可。
问题2:如何保存一条路径? 把一个arrayList对象 作为一个参数传给DFS( )递归函数,在遍历的每一步,把路径上的节点放心去。 当我们找到一个路径的时候,把整条路径拷贝给 List res ; 这里注意一点,保存临时路径的是一个对象,不能直接放进res 中,因为对象在外面有变化,会影响到里面。 同时由于我们这是一个回溯算法,必须在一次递归结束后,把当前的节点从临时保存路径的List 中退出来。
问题3:如何对最后的结果进行排序? 按照下标位置 逐个比较元素的大小。下标的最大范围必须为路径中较短的那条路径的长度 。
问题4:Java可以通过时间限制吗? 比较幸运,这次能通过。
完整代码:
import java.util.*;
// date : 3/10
//score : 30 /30
// 20 9 24
//10 2 4 3 5 10 2 18 9 7 2 2 1 3 12 1 8 6 2 2
//00 4 01 02 03 04
//02 1 05
//04 2 06 07
//03 3 11 12 13
//06 1 09
//07 2 08 10
//16 1 15
//13 3 14 16 17
//17 2 18 19
public class P1053 {
static List<List<Integer>> res = new ArrayList<>(); // 里面存放的是路径的权重
static boolean[] Isparent; // 当前的节点是不是一个非叶子节点,也就是说是不是某个节点的父节点
static int[] wight; //存储所有节点的权重
static int target; // 题目给定的目标权重和
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int nodeNum = scanner.nextInt(); // 总共的节点个数
int noleftnum = scanner.nextInt(); // 非叶子节点的个数
target = scanner.nextInt(); // 给定的目标权重和
scanner.nextLine(); // 吸收一下换行符
// 数组初始化操作
wight = new int[nodeNum];
Isparent = new boolean[nodeNum];
for (int i = 0; i < nodeNum; i++) {
wight[i] = scanner.nextInt(); // 所有结点的权重
}
scanner.nextLine();
int[][] tree = new int[nodeNum][nodeNum]; // 树的邻接矩阵
for (int j = 0; j < noleftnum; j++) {
int ID = scanner.nextInt();
Isparent[ID] = true; // 这是一个父节点
int childnum = scanner.nextInt();
for (int k = 0; k < childnum; k++) {
int childID = scanner.nextInt();
tree[ID][childID] = 1; // 树可以认为是有向无环图
}
scanner.nextLine();
}
List<Integer> wightlist = new ArrayList<>(); //wightList 用于保存临时路径初始为空
DFS(tree, 0, wight[0], wightlist); //我们从根节点0开始进行搜索
// 对结果进行排序
Collections.sort(res, new Comparator<List<Integer>>() {
@Override
public int compare(List<Integer> o1, List<Integer> o2) {// 如果o1比 o2 大 o1 会排在后面
int length = Math.min(o1.size(), o2.size());
for (int i = 0; i < length; i++) {
if (o1.get(i) != o2.get(i))
return o2.get(i) - o1.get(i);
}
return 0;
}
});
// 对结果进行输出
for (int k = 0; k < res.size(); k++) {
for (int m = 0; m < res.get(k).size(); m++) {
System.out.print(res.get(k).get(m));
if (m != res.get(k).size() - 1)
System.out.print(" ");
}
if (k != res.size() - 1)
System.out.println();
}
}
// 路径搜索函数
static void DFS(int[][] tree, int start, int totalwight, List<Integer> wightlist) {
if (!Isparent[start]) { // 如果start 是一个叶子节点
wightlist.add(wight[start]); // 那么就把start 的权重放入路径中
if (totalwight == target) // 如果这条路径符合要求 我们就把它放入res 结果中 然后返回
res.add(new ArrayList<>(wightlist));
return;
}
//如果start 不是一个叶子节点,换言之还没有找到一条完整的路径
wightlist.add(wight[start]); // 我就先把start的权重放入路径中
for (int i = 0; i < tree.length; i++) {
if (tree[start][i] == 1 ) {
DFS(tree, i, totalwight + wight[i], wightlist);
// 比较难的地方在这里,每次从递归函数出来后,我们需要把刚刚加入的节点权重退出来
// 回溯算法的精妙之处,我个人觉得在这个地方有体现
wightlist.remove(wightlist.size() - 1);
}
}
}
}