1053. Path of Equal Weight
来源:互联网 发布:vs2013 c语言入门教程 编辑:程序博客网 时间:2024/05/07 15:34
http://pat.zju.edu.cn/contests/pat-a-practise/1053
链表的操作,dfs遍历
#include <stdio.h>#include <iostream>#include <vector>#include <malloc.h>#include <algorithm>using namespace std;struct Node {int weight;vector<Node* > next; //节点的孩子向量,保存node指针型};vector<int> ans; //保存路径上结点权值vector<int> weight; //保存权值int total; //给定的路径和bool cmp(Node* A,Node* B){return A->weight>B->weight;}void dfs(Node* curNode,int cur) //深度遍历{int i,j; cur+=curNode->weight; if (curNode->next.size()==0) //孩子向量空,说明是叶子节点 { if (cur==total) { for (i=0;i<ans.size();i++) { if (i==0) { printf("%d",ans[i]); } else { printf(" %d",ans[i]); } } printf("\n"); } return; } else { if (cur>total) //还未到叶子,却已经超过给定权值,直接返回 { return; } else { sort(curNode->next.begin(),curNode->next.end(),cmp); //对所有孩子节点大小排序,先遍历权值大的 for (j=0;j<curNode->next.size();j++) { ans.push_back(curNode->next[j]->weight); //当前节点先放进结果中向量中,若满足就返回,否则到上一层,再pop出来 dfs(curNode->next[j],cur); ans.pop_back(); } } }}int main(){ int n,m,i,j;scanf("%d%d%d",&n,&m,&total);vector<Node*> buf(n); //声明向量时就声明大小,就可以对下标操作 for (i=0;i<n;i++){int x; scanf("%d",&x); weight.push_back(x); } for (i=0;i<n;i++) {buf[i]=new Node;buf[i]->weight=weight[i]; }for (i=0;i<m;i++){ int id,k; //该非叶节点有k个孩子 scanf("%d%d",&id,&k); for (j=0;j<k;j++) { int child; scanf("%d",&child); buf[id]->next.push_back(buf[child]); }}ans.push_back(buf[0]->weight); //根节点肯定在路径上int cur=0; //保存当前权值和 dfs(buf[0],cur);return 0;}//因为输入无序,所以先输入权值,再保存在相应节点//不要输入孩子时输入权值
- 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
- 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)
- 1053. Path of Equal Weight (30)
- 1053. Path of Equal Weight (30)
- 1053. Path of Equal Weight (30)
- 第三周上机任务项目4-长方柱类
- 机器学习中的算法(2)-支持向量机(SVM)基础
- Win7 "未识别网络" 的20种常见解决方案
- OpenGL——纹理
- 数论概论笔记 第6章 线性方程与最大公因数
- 1053. Path of Equal Weight
- 看面霸有感
- QEMU中的qemu_thread_create函数
- linux NFS suage
- usaco-dualpal-1.2宣告结束
- zoj 1037 python
- 数据挖掘学习札记:KNN算法(三)
- OLEDB 连接 SQLSERVER 2005
- ubuntu学习