Given a non-empty tree with root R, and with weight Wi assigned to each tree node Ti. 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 , the number of nodes in a tree, , the number of non-leaf nodes, and , the given weight number. The next line contains N positive numbers where corresponds to the tree node . 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 is said to be greater than sequence if there exists such that for , and .
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
Ω
输出所有从根节点到叶子结点权重和为给定值的权重路径。
其实上面这个真的小儿科,不管是DFS还是BFS都三下五除二,这个输出顺序是真的麻烦,害得我重构了两次。
讲讲我的心路历程吧。一开始想的比较粗糙,觉得输出顺序应该和BFS是一致的,所以上来就BFS找到权重和符合要求的所有叶子结点,根据父节点进行回溯然后依次输出。然后就发现最先输出的只能说明路径上的节点数是最少的,中间节点的权重也可以较小。
转念一想,输出顺序的思想是每次先找权重较大的节点进行遍历,事实上与DFS是一致的,我们只需要将便利的顺序先对权重排序一遍即可。于是乎简单地重构了下代码,还是很快的,春风拂面,小手一点。唯有最后一个测试点是绿的,百思不得其解,夜深了,看了些网上的题解,豁然开朗,问题就在于对权重相同节点的便利顺序是不确定的,最典型的栗子如下图所示,由于第二层权重相等,因此可能会先往左边遍历。
当然实在不行我们就先一股脑儿找到所有节点最后再一起排个序,但没什么意思。我想借助并查集的思想,将属于同一个父节点而且权重相同的子节点进行合并,即一个节点不会存在权重一样的子节点,如此一来就可以把这些同权异父同爷(这些父节点的父节点相同)的子节点放在一起sort了。
大致流程如下:
设置一个 向量,用来表示节点 将自己所有子节点托付给同权同父的 节点
⚠️我们需要将叶节点的属性也一并托付,让DFS知道这个节点也能作为叶子节点:
每读入非叶子节点的子节点时,建立一个权重到节点编号的map映射, 表示当前节点已存在权重为 的子节点 ,之后对所有权重为 的子节点 ,都采取 ;若不存在该权重映射则
对所有节点更新父节点: ,然后将该节点压入真正父节点的孩子向量中: .push_back( )
对所有节点的子节点根据权重进行降序排序
从根节点开始DFS,最后依次回溯输出权重路径
🐎🧬
BFS
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n, m, s, id, k, child;
cin >> n >> m >> s;
vector<int> weight(n), dad(n, -1), ans, nxt, crt, sum(n, 0);
for (auto &w: weight)
cin >> w;
sum[0] = weight[0];
vector<vector<int>> children(n);
for (int i = 0; i < m; ++i)
{
cin >> id >> k;
for (int j = 0; j < k; ++j)
{
cin >> child;
dad[child] = id;
children[id].push_back(child);
}
}
crt = children[0];
while (!crt.empty())
{
for (auto &c: crt)
{
sum[c] += sum[dad[c]] + weight[c];
if (sum[c] == s && children[c].empty())
ans.push_back(c);
else if (sum[c] < s)
nxt.insert(nxt.end(), children[c].begin(), children[c].end());
}
crt = std::move(nxt);
nxt = vector<int>();
}
vector<int> path;
for (auto c: ans)
{
path.push_back(weight[c]);
while (dad[c] != -1)
{
c = dad[c];
path.push_back(weight[c]);
}
for (auto item = path.rbegin(); item < path.rend(); ++item)
cout << (item == path.rbegin() ? "" : " ") << *item;
cout << endl;
path.clear();
}
}
DFS
#include <iostream>
#include <vector>
#include <map>
#include <numeric>
#include <algorithm>
using namespace std;
vector<int> weight, ans, sum;
vector<vector<int>> children;
vector<bool> isLeaf;
void search(int papa, int &s)
{
if (sum[papa] == s && isLeaf[papa])
ans.push_back(papa);
for (auto k: children[papa])
{
sum[k] = weight[k] + sum[papa];
if (sum[k] <= s)
search(k, s);
}
}
int main()
{
int n, m, s, id, k, child;
cin >> n >> m >> s;
vector<int> dad(n, -1), real;
weight.resize(n);
sum.resize(n, 0);
isLeaf.resize(n, true);
real.resize(n);
iota(real.begin(), real.end(), 0);
for (auto &w: weight)
cin >> w;
sum[0] = weight[0];
for (int i = 0; i < m; ++i)
{
cin >> id >> k;
isLeaf[id] = false;
map<int, int> idx;
for (int j = 0; j < k; ++j)
{
cin >> child;
if (idx.find(weight[child]) == idx.end())
idx[weight[child]] = child;
else
{
real[child] = idx[weight[child]];
isLeaf[real[child]] = isLeaf[real[child]] || isLeaf[child];
}
dad[child] = real[id];
}
}
children.resize(n);
for (int i = 1; i < n; ++i)
{
dad[i] = real[dad[i]];
children[dad[i]].push_back(i);
}
for (auto &v: children)
sort(v.begin(), v.end(), [](int &a, int &b) { return weight[a] > weight[b]; });
search(0, s);
vector<int> path;
for (auto c: ans)
{
path.push_back(weight[c]);
while (dad[c] != -1)
{
c = dad[c];
path.push_back(weight[c]);
}
for (auto item = path.rbegin(); item < path.rend(); ++item)
cout << (item == path.rbegin() ? "" : " ") << *item;
cout << endl;
path.clear();
}
}
Tips
给一个vector增序赋值:
#include <numeric> …… vector<int> v(num); //需要先确定向量大小 iota(v.begin(),v.end(),start);
最终就会得到
将vector v1插入到v2的最后:
v2.insert(v2.end(), v1.begin(), v1.end());