A1053 Path of Equal Weight

强调:在读入时对每个结点的所有子结点按权值从大到小排序,这样在递归的过程中总是会先访问所有子结点中权值更大的

#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn=110;
struct node
{
	int weight;
	vector<int> child;
}Node[maxn];

bool cmp(int a,int b)///***
{
	return Node[a].weight>Node[b].weight;///对一个结点的每个子结点的权值排序 
}
int n,m,s; 
int path[maxn];
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]].weight);
			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;  ///***下标与个数正好差1 
		DFS(child,numNode+1,sum+Node[child].weight);
		
	}
	
}
int main()
{

	int weight;
	int parent,k,child;
	scanf("%d%d%d",&n,&m,&s);
	for(int i=0;i<n;i++)
	{
		scanf("%d",&Node[i].weight);
	}
	for(int i=0;i<m;i++)
	{
		scanf("%d%d",&parent,&k);
		for(int j=0;j<k;j++)
		{
			scanf("%d",&child);
			Node[parent].child.push_back(child);   ///***
		}
		sort(Node[parent].child.begin(),Node[parent].child.end(),cmp);///***存放的是每个结点的子结点标号 
	}
	DFS(0,1,Node[0].weight);  ///**** 
	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值