顽强的小白
1053 Path of Equal Weight (30 分)
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.
题目解析
找到路径权值之和为题目要求的路径
代码实现
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn=105;
struct {
int weight;
vector<int> child;
}node[maxn];
int n,m,s;
vector<int> tmp; //储存 路径结点信息
bool cmp(int a,int b){
return node[a].weight>node[b].weight;
}
void DFS(int index,int sum){
if(sum>s) return; //这条路径权值太大了
if(sum==s){ //满足和的要求
if(node[index].child.size()==0){ //还要判断是不是到叶结点了
for(int i=0;i<tmp.size();++i){ //直接在这里输出
printf("%d",node[tmp[i]].weight);
if(i<tmp.size()-1) printf(" ");
else printf("\n");
}
}
return;
}
for(int i=0;i<node[index].child.size();++i){ //遍历所有孩子
int child=node[index].child[i];
tmp.push_back(child); //走这个孩子的分支
DFS(child,sum+node[child].weight);
tmp.pop_back(); //走完这个分支就退回来
}
}
int main(){
scanf("%d%d%d",&n,&m,&s);
for(int i=0;i<n;++i){
scanf("%d",&node[i].weight);
}
int k,child,now;
for(int i=0;i<m;++i){
scanf("%d%d",&now,&k);
for(int j=0;j<k;++j){
scanf("%d",&child);
node[now].child.push_back(child);
}
sort(node[now].child.begin(),node[now].child.end(),cmp);
//一定要记得要把孩子们按照权值从大到小排序
//不然就会按照编号大小,输出的结果不满足要求
}
tmp.push_back(0); //添上根结点
DFS(0,node[0].weight) ; //根节点的权值也要有
return 0;
}