PAT_1053. Path of Equal Weight
来源:互联网 发布:诸神黄昏天梭进阶数据 编辑:程序博客网 时间:2024/06/01 10:31
//// main.cpp// PAT_1053. Path of Equal Weight//// Created by wjq on 17/5/14.// Copyright © 2017年 wjq. All rights reserved.//#include <iostream>#include <vector>#include <algorithm>using namespace std;int N,M,S,father,numofkids;struct node{ vector<int> next; int weight;}n[105];int nextWeight[105];int sumofweight=0;void dfs(int now,int sum){ if(n[now].next.empty()==true) //必须到叶节点才会检查sum是否等于S. { sum+=n[now].weight; nextWeight[sumofweight++]=n[now].weight; if(sum==S) { for(int i=0;i<sumofweight;i++) { if(i!=sumofweight-1) cout<<nextWeight[i]<<" "; else cout<<nextWeight[i]<<endl; } } nextWeight[sumofweight--]=0; return; } for(int i=0;i<n[now].next.size();i++) { nextWeight[sumofweight++]=n[now].weight; dfs(n[now].next[i],sum+n[now].weight); nextWeight[sumofweight--]=0; }}int cmp(int a,int b){ return n[a].weight>n[b].weight;}int main(int argc, const char * argv[]){ cin>>N>>M>>S; for(int i=0;i<N;i++) cin>>n[i].weight; for(int i=0;i<M;i++) { cin>>father>>numofkids; int kid[105]; for(int j=0;j<numofkids;j++) cin>>kid[j]; sort(kid,kid+numofkids,cmp); //从大到小排. for(int j=0;j<numofkids;j++) { n[father].next.push_back(kid[j]); } } dfs(0,0); return 0;}
终于感觉到自己的进步了,很快就把dfs写好了,没有参照网上的代码.一次就过了!
题意:
就是说给你一棵树,树上每个节点有编号和权重两个属性.然后给你一个权值S,让你输出从根节点到叶节点的权重和=S的那些节点的权重.当然结果不止一个,输出顺序按照题意的描述.
思路:建树,dfs,在dfs过程中计算权值,每当到达子节点并且权值和=S的时候输出该路径的所有节点的权重.
考虑到题目中的输出顺序,我们在建树的时候就把权重大的结点放在左边.这样dfs的时候就能先访问到权重相对较大的节点.
0 0
- PAT_1053: Path of Equal Weight
- PAT_1053. Path of Equal Weight
- Path of Equal Weight
- 1053. Path of Equal Weight
- 1053. Path of Equal Weight
- 1053. Path of Equal Weight
- 1053. Path of Equal Weight
- 1053.Path of Equal Weight
- 1053. Path of Equal Weight
- 1053 path of equal weight
- 1053. Path of Equal Weight
- 1053. Path of Equal Weight
- 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
- PAT 1053. Path of Equal Weight (30)
- 二分法(c语言)
- Udeitor图片、文件等上传的实现
- MMD :maximum mean discrepancy(最大平均差异)
- 手把手教你,安装win7全部流程,图文结合
- javascript的typeof
- PAT_1053. Path of Equal Weight
- 95. Unique Binary Search Trees II
- 学习笔记| AS入门(四) 组件篇之Activity
- ubuntu下burpsuite安装
- 【数据结构】二叉搜索树
- java.lang.IllegalArgumentException: Document base
- k近邻算法及其实例(实战笔记一)
- 虚拟机搭建CDH-第五讲-克隆虚拟机
- STM32F103的11个定时器详解 高级定时器pwm