PAT A1053 Path of Equal Weight(广义树DFS,preOrder)

题目地址https://pintia.cn/problem-sets/994805342720868352/problems/994805424153280512

#include <iostream>
#include <string>
#include <set>
#include <map>
#include<queue>
#include<stack>
#include<algorithm>

//new and delete
//A1053 Path of Equal Weight
using namespace std;

typedef int ElemType;
const int MaxN = 120;
struct node {
	ElemType w;		//weight
	vector<int> child;
}Node[MaxN];

bool cmp(int child1,int child2) {
	//权值大的孩子排在前面
	return Node[child1].w > Node[child2].w;
}
vector<int>temp;	//路径暂存
//从root开始递归访问,得到路径序号temp,存储到ans(注意加引用)
void DFS(int S, vector<vector<int> > &ans,int w_sum,int root) {
	w_sum += Node[root].w;
	//cout << w_sum << endl;
	//cout << "root:" << root << endl;
	if (w_sum > S )
		return;

	temp.push_back(root);
	//得到一条路径
	if (w_sum == S && Node[root].child.empty()) {
		ans.push_back(temp);
		temp.pop_back();
		return;
	}
	//递归访问孩子,这里从右往左
	if (!Node[root].child.empty()) {
		vector<int>::iterator it = Node[root].child.begin();
		sort(it, Node[root].child.end(), cmp);
		for (it= Node[root].child.begin(); it!= Node[root].child.end(); it++)
			DFS(S, ans, w_sum, *it);
	}
	temp.pop_back();
	return;
}

int main() {
	//freopen( "input.txt", "r", stdin);

	//N:the number of nodes in a tree
	//M:the number of non-leaf nodes
	//S:the given weight number
	int N, M, S;

	//data input
	cin >> N >> M >> S;
	for (int i = 0; i < N; i++)
		cin >> Node[i].w;
	for (int i = 0; i < M; i++) {
		int index,child_num;
		cin >> index >> child_num;
		for (int j = 0; j < child_num; j++) {
			int child_1;
			cin >> child_1;
			Node[index].child.push_back(child_1);
		}
	}

	vector<vector<int> > ans;	//存储符合条件的序列
	DFS(S, ans, 0, 0);

	for (int i = 0; i < ans.size(); i++) {
		for (int j = 0; j < ans[i].size(); j++) {
			cout << Node[ans[i][j]].w;
			if (j == ans[i].size() - 1)
				cout << endl;
			else
				cout << " ";
		}
	}
	
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值