PAT A1053 Path of Equal Weight

本文介绍了一种基于树形结构的深度优先搜索(DFS)算法,用于寻找所有可能的路径,使得路径上节点的权值之和等于给定的数值。通过递归方式遍历树的每一个节点,并利用回溯思想,有效地解决了路径查找问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<cstdio> 
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 110;
int weight[maxn];
int n; //the number of nodes in a tree
int m; //the number of non-leaf nodes
int s; // the given weight number
struct node{
	int data;
	vector<int> child;
	int leaf; //1为叶子节点 
}Node[maxn];

int path[maxn]; //记录路径 
//当前访问节点为index, numNode为当前path上的结点个数 
//sum为当前结点的权值之和 
void DFS(int index, int numNode, int sum){
	if(sum > s) return;
	if(sum == s){
		if(Node[index].child.size() != 0) return;
		for(int i=0;i<numNode;i++){
			printf("%d",Node[path[i]].data);
			if(i < numNode - 1) printf(" ");
			else printf("\n");
		}
		return;
	}
	for(int i=0;i<Node[index].child.size();i++){
		int child = Node[index].child[i];
		path[numNode] = child;
		DFS(child,numNode+1,sum+Node[child].data);
	}
}


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

int main(){
	int value;
	int non_leaf,non_leaf_num;
	scanf("%d %d %d",&n,&m,&s);
	for(int i=0;i<n;i++){
		scanf("%d",&weight[i]);
		Node[i].data = weight[i];
		Node[i].leaf = 1;//先都设为叶子节点 
	}
	for(int i=0;i<m;i++){
		scanf("%d %d",&non_leaf,&non_leaf_num);
		Node[non_leaf].leaf = 0;//这些都为非叶子节点 
		for(int j=0;j<non_leaf_num;j++){
			scanf("%d",&value);
			Node[non_leaf].child.push_back(value);
		}
		sort(Node[non_leaf].child.begin(),Node[non_leaf].child.end(),cmp);
	}
	path[0] = 0;
	DFS(0,1,Node[0].data);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值