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