[C++] PAT 1053 Path of Equal Weight (30分)

在这里插入图片描述

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

题解:

使用了静态结构体数组去构件树结构,数组下标为树的结点标志,内容为该节点的weight及其child。
在树生成的过程中就按照其child的weight从大到小对其child行了了排序,后面输出时就能够直接输出,减少了排序的过程。
遍历时采用了vector来存储遍历过的结点,同时用到了回溯的思想。

#include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
const int MAXN = 110;
using namespace std;



struct node{
	int data;
	vector<int> child;
}Node[MAXN];

bool cmp(int a,int b){
	return Node[a].data > Node[b].data;
}


int number;
int non_leaf_num;
int need_sum;
vector<int> path;


void DFS(int root,int sum){
	path.push_back(root);

	if(sum > need_sum){
		return;
	}
	
	if(sum == need_sum){
		if(Node[root].child.size() != 0){
			return;
		} 
		for(int i = 0;i < path.size();i++){
			cout << Node[path[i]].data;
			if(i == path.size()-1) cout << endl;
			else cout << " ";
		}
	}

	for(int i=0;i < Node[root].child.size();i++){
		int ch = Node[root].child[i];
		
		DFS(ch,sum+Node[ch].data);

		path.pop_back();
	}


}

int _1053(){
	cin >> number >> non_leaf_num >> need_sum;

	for(int i =0;i < number;i++){
		scanf_s("%d",&Node[i].data);
	}


	int id,child_num,child;
	for(int i =0;i < non_leaf_num;i++){
		
		cin >> id;
		cin >> child_num;
	
		for(int k = 0;k < child_num;k++){
			cin >> child;
			Node[id].child.push_back(child);	
		}

		sort(Node[id].child.begin(),Node[id].child.end(),cmp);
	}

	DFS(0,Node[0].data);

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值