ZOJ 3516 Tree of Three(DFS)
2012-05-10 21:28
375 查看
题目链接:Click
here~~
题意:给一棵树,有n个节点(编号:0~n-1),每个节点有一个权值,0为树根,找出某个节点所在子树的最大的3个值。
解题思路:树根已经确定,所以问题也变的比较简单,只需要先确定叶子节点的最值,依次向父节点传递影响,直到根节点。则很容易想到用深搜来实现。
here~~
题意:给一棵树,有n个节点(编号:0~n-1),每个节点有一个权值,0为树根,找出某个节点所在子树的最大的3个值。
解题思路:树根已经确定,所以问题也变的比较简单,只需要先确定叶子节点的最值,依次向父节点传递影响,直到根节点。则很容易想到用深搜来实现。
#include <vector> #include <stdio.h> #include <string.h> #include <algorithm> #define Max 10005 #define CLR(arr,val) memset(arr,val,sizeof(arr)) using namespace std; vector <int> V[Max]; int n,ans[Max][7]; bool cmp(int a,int b) { return a > b; } void dfs(int x) { while(!V[x].empty()) { int p = V[x].back(); V[x].pop_back(); dfs(p); for(int i=3;i<6;i++) ans[x][i] = ans[p][i-3]; sort(ans[x],ans[x]+6,cmp); } } int main() { int a,b,Q,x; while(~scanf("%d",&n)) { CLR(ans,-1); scanf("%d",&ans[0][0]); for(int i=1;i<n;i++) { scanf("%d%d",&a,&b); V[a].push_back(i); ans[i][0] = b; } dfs(0); scanf("%d",&Q); while(Q--) { scanf("%d",&x); if(ans[x][2] == -1) printf("-1\n"); else printf("%d %d %d\n",ans[x][0],ans[x][1],ans[x][2]); } } return 0; }
相关文章推荐
- ZOJ --- 3516 Tree of Three
- zoj 3516 Tree of Three
- ZOJ 3516 Tree of Three
- ZOJ3516 Tree of Three,DFS
- ZOJ Monthly, July 2011 - G Tree of Three 3516
- [leetcode][tree][dfs] Minimum Depth of Binary Tree
- ZOJ 2110 Tempter of the Bone(条件迷宫DFS,HDU1010)
- zoj 3170 7 Levels of Binary Search Tree(BST)
- zoj-2110-Tempter of the Bone-DFS-剪枝-java
- HDU 1010 Tempter of the Bone &&ZOJ 2110【DFS】
- zoj 3170 7 Levels of Binary Search Tree(BST = =)
- [LeetCode] Minimum Depth of Binary Tree - DFS
- ZOJ-#3516Tree of Three(dfs+vector)
- CF804D:Expected diameter of a tree(树的直径 & dfs)
- zoj 2110 Tempter of the Bone (dfs)
- leetcode 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树BST的最近公共祖先LCA + 深度优先遍历DFS
- leetcode 104 Maximum Depth of Binary Tree(DFS)
- ZOJ 3201 Tree of Tree
- TOJ 2676 ZOJ 3201 Tree of Tree / 树形DP
- zoj 3965 Binary Tree Restoring(* dfs)