1053. Path of Equal Weight (30)
来源:互联网 发布:ubuntu 添加路由 编辑:程序博客网 时间:2024/06/07 10:03
题目链接:https://www.patest.cn/contests/pat-a-practise/1053
题目大意:给定一个权值和sum,在所有从树的根节点到叶子结点的路径中,选出路径的权值和等于sum的所有路径。
思路:深度优先遍历所有路径,找出满足条件的路径。注意DFS函数的结束条件
代码如下(有详细注释)
#include <iostream>#include <cstdio>#include <algorithm>#include <vector>using namespace std;struct node{ int w;//权值 vector<int> child;//孩子节点的下标};int sum;//路径和vector<node> v;//记录树的每个节点,下标为序号vector<int> path;//元素值为节点的序号,也即在v中的下标void DFS(int index,int pathcount,int currentsum){ /*深度优先地遍历整棵树。 index为当前数的根节点的下标; pathcount为当前节点属于当前路径的第几个节点 sum为当前路径的部分权值和*/ if(currentsum>sum)//当前权值和超出要求 return; if(currentsum==sum){//权值和已满足要求 if(v[index].child.size()!=0)//但该节点不是叶子结点 return; for(int i=0;i<pathcount;i++){ if(i==pathcount-1) cout<<v[path[i]].w<<endl; else cout<<v[path[i]].w<<" "; } } /*权值和还未达到目标值,深度优先地遍历该节点的每一个孩子*/ for(int i=0;i<v[index].child.size();i++){ int tmp=v[index].child[i]; path[pathcount]=tmp; DFS(tmp,pathcount+1,currentsum+v[tmp].w); }}bool cmp(int a,int b){ return v[a].w>v[b].w;}int main(int argc, char const *argv[]){ int n,m; cin>>n>>m>>sum; v.resize(n); path.resize(n); for(int i=0;i<n;i++) cin>>v[i].w; for(int i=0;i<m;i++){ int tmp,cnt; scanf("%02d %d",&tmp,&cnt); v[tmp].child.resize(cnt); for(int j=0;j<cnt;j++){ scanf("%02d",&v[tmp].child[j]); } sort(v[tmp].child.begin(),v[tmp].child.end(),cmp);//此处排序是为了满足输出要求 } DFS(0,1,v[0].w); return 0;}
阅读全文
0 0
- 1053. Path of Equal Weight (30)
- 1053. Path of Equal Weight (30)-PAT
- 1053. Path of Equal Weight (30)
- 1053. Path of Equal Weight (30)
- PAT 1053. Path of Equal Weight (30)
- 1053. Path of Equal Weight (30)
- 1053. Path of Equal Weight (30)
- 1053. Path of Equal Weight (30)
- 1053. Path of Equal Weight (30)
- PAT 1053. Path of Equal Weight (30)
- 1053. Path of Equal Weight (30)
- 1053. Path of Equal Weight (30)
- 1053. Path of Equal Weight (30)
- 1053. Path of Equal Weight (30)
- PAT 1053. Path of Equal Weight (30)
- 1053. Path of Equal Weight (30)
- 1053. Path of Equal Weight (30)
- 1053. Path of Equal Weight (30)
- 数据结构之贪心算法(背包问题的思考)
- STL 中的Map用法
- eclipse 中的注释 快捷键 多行注释快捷键 单行注释快捷键
- 基于Dragonboard 410c的智能遥控器(一)
- 泛型依赖注入
- 1053. Path of Equal Weight (30)
- 关于使用hibernate中遇到的问题
- Spyder Ipython Console卡在Connecting to kernel的解决方案
- postgresql----Btree索引
- 数据库利器Navicat最全快捷键整理
- 安卓一键清理工具
- MIR7/MIRO 贷项凭证/事后借记/后续贷记
- Android AMS 浅析
- ubuntu14.04 samba没有权限访问解决