数据结构专题06 树

example1

  • https://pintia.cn/problem-sets/994805342720868352/problems/994805424153280512
    在这里插入图片描述

在这里插入图片描述

#include<iostream>
#include<algorithm>
#include<vector>
#define maxSize 100
using namespace std;
int flag = 0;//输出的时候,0代表还没有输出,所以前面不用加endl
typedef struct {
	int weight;
	int childrenList[maxSize];
	int childrenNum;
}Tree;
Tree tree[maxSize];//这里设置为全局变量是因为cmp需要
bool cmp(const int a, const int b) {
	return tree[a].weight > tree[b].weight;
}

void DFS(Tree tree[], int givenWeightNumber, int root, int sum, vector<int>& roads) {
	roads.push_back(tree[root].weight);
	sum += tree[root].weight;
	if (sum == givenWeightNumber) {
		if (tree[root].childrenNum != 0) {
			//路径权值正好够,但是还没有到叶子节点
			return;
		}
		//可以输出了
		for (int i = 0; i < roads.size(); ++i) {
			if (i == 0) {
				if (flag == 0) {
					flag = 1;
				}
				else {
					cout << endl;
				}
				cout << roads.at(i);
			}
			else {
				cout << " " << roads.at(i);
			}
		}
	}
	else {
		for (int i = 0; i < tree[root].childrenNum; ++i) {
			DFS(tree, givenWeightNumber, tree[root].childrenList[i], sum, roads);
			roads.pop_back();
		}
	}
}
int main() {
	int nodesNum;
	int nonLeafNodesNum;
	int givenWeightNumber;
	cin >> nodesNum >> nonLeafNodesNum >> givenWeightNumber;
	for (int i = 0; i < maxSize; ++i) {
		tree[i].childrenNum = 0;//初始化为0 
	}
	for (int i = 0; i < nodesNum; ++i) {
		cin >> tree[i].weight;
	}
	for (int i = 0; i < nonLeafNodesNum; ++i) {
		int id;
		int childrenNum;
		cin >> id >> childrenNum;
		tree[id].childrenNum = childrenNum;
		for (int j = 0; j < childrenNum; ++j) {
			cin >> tree[id].childrenList[j];
		}
		sort(tree[id].childrenList, tree[id].childrenList + childrenNum,cmp);//排序,以便于最后输出按从大到小 
	}//输入完毕
	vector<int> roads;
	DFS(tree, givenWeightNumber, 0, 0, roads);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值