1053. Path of Equal Weight

经典的树的遍历问题,在插入每个非叶节点的邻接点时,维护一个优先队列,优先插入数据比较大的节点,从而在实施搜索时一旦碰到叶子节点,且该路径上数据总和为所需值时,直接输出该路径上的各数据。

// 1053. Path of Equal Weight.cpp: 主项目文件。

#include "stdafx.h"
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;

const int N=103;
int hashTable[N];
bool used[N];
int needSum;

typedef struct Node{
	int flag,data;
}Node;

struct cmp{
	bool operator()(Node m1,Node m2){
		return m1.data<m2.data;
	}
};

vector<Node> edge[N]; 
priority_queue<Node,vector<Node>,cmp> Q;
vector<Node> path;

void dfs(int cur,int curSum){
	used[cur]=true;
	if(edge[cur].size()==0&&curSum==needSum){
		for(vector<Node>::iterator ite=path.begin();ite!=path.end();ite++){
			if(ite!=path.begin())
				printf(" ");
			printf("%d",ite->data);
		}
		printf("\n");
	}
	for(vector<Node>::iterator ite=edge[cur].begin();ite!=edge[cur].end();ite++){
		if(!used[ite->flag]){
			path.push_back(*ite);
			dfs(ite->flag,curSum+ite->data);
			path.pop_back();
		}
	}
}

int main()
{
	int nodes,nonLeafNodes;
	scanf("%d%d%d",&nodes,&nonLeafNodes,&needSum);
	for(int i=0;i<nodes;i++)
		scanf("%d",hashTable+i);
	for(int i=0;i<nonLeafNodes;i++){
		int from,num;
		scanf("%d%d",&from,&num);
		while(!Q.empty())
			Q.pop();
		while(num--){
			int tFlag,tData;
			scanf("%d",&tFlag);
			tData=hashTable[tFlag];
			Node node;
			node.flag=tFlag,node.data=tData;
			Q.push(node);
		}
		while(!Q.empty()){
			Node tNode=Q.top();
			edge[from].push_back(tNode);
			Q.pop();
		}
	}
	memset(used,0,sizeof(used));
	Node root;
	root.flag=0,root.data=hashTable[0];
	path.push_back(root);
	dfs(0,hashTable[0]);
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值