SPOJ_PT07Z 树最长路径问题
来源:互联网 发布:淘宝him折扣店是真的吗 编辑:程序博客网 时间:2024/05/16 11:23
1. 题面
You are given an unweighted, undirected tree. Write a program to output the length of the longest path (from one node to another) in that tree. The length of a path in this case is number of edges we traverse from source to destination.
Input
The first line of the input file contains one integer N — number of nodes in the tree (0 < N <= 10000). Next N-1 lines contain N-1 edges of that tree — Each line contains a pair (u, v) means there is an edge between node u and node v (1 <= u, v <= N).
Output
Print the length of the longest path on one line.
Example
Input:
3
1 2
2 3Output:
2
2.思路
- 构造三维数组存储每个节点 ①最长路 ②最长边 ③次长边
- 使用vector存储相邻结点地址
- DFS更新最长路,即为答案
3.代码
#include <iostream>#include <vector>using namespace std;int check[10000 + 5];int treenode[10000 + 5][3];int n, m,ans=1;void dfs(vector<int> *nodelink , int i) { if (nodelink[i].size() == 1) return; int n1=0, n2=0; for (int k = 0; k < nodelink[i].size(); k++) { check[i]++; int temp = nodelink[i][k]; if (!check[temp]) { dfs(nodelink, temp); if (treenode[i][1] < treenode[temp][1]) { treenode[i][2] = treenode[i][1]>treenode[i][2]?treenode[i][1]:treenode[i][2]; treenode[i][1] = treenode[temp][1]; } else { if (treenode[i][2]<treenode[temp][1]) treenode[i][2] = treenode[temp][1]; } } } treenode[i][1]++; treenode[i][2]++; treenode[i][0] = treenode[i][1] + treenode[i][2]; ans = treenode[i][0] > ans ? treenode[i][0] : ans;}int main() { while (cin >> n) { vector<int> nodelink[10000+5]; int u, v; for (int i = 0; i < n-1; i++) { cin >> u >> v; nodelink[u].push_back(v); nodelink[v].push_back(u); } int k = 1; for (; k < n + 1; k++) if (nodelink[k].size()>1) break; dfs(nodelink,k); cout << ans << endl; ans = 0; for (int i = 0; i < n + 1; i++){ treenode[i][0] = 0; treenode[i][1] = 0; treenode[i][2] = 0; check[i] = 0; } } return 0;}
4.所得
- 题意与PT07Y相似,改进处为 用vector存储结点地址
0 0
- SPOJ_PT07Z 树最长路径问题
- 二叉树最长路径问题
- 最长路径问题dp
- 二叉树最长路径
- 树中的最长路径
- nowcoder 树上最长单色路径(最长路径,二叉树+dp)
- 二叉树的最长路径
- 二叉树的最长路径
- 二叉树的最长路径
- 二叉树的最长路径
- 最长路径
- 最长路径
- 历届试题 大臣的旅费 (树的最长路径问题:两次BFS)
- JAVA 树中 按最长路径行驶
- 求树中最长路径 树的直径
- 求一个树的最长路径
- 求树的直径(最长路径)
- hiho 11 树的最长路径
- 解决error: Your local changes to the following files would be overwritten by merge
- 计算机概述,键盘快捷键,常见的DOS命令,Java语言概述,JDK、JRE、JVM之间的关系,环境变量的配置
- Tomcat的性能优化及部署时的参数调整
- Spring配置文件加载流程
- Unsupported major.minor version 51.0解决办法
- SPOJ_PT07Z 树最长路径问题
- Spring classPath:用法
- node.js实现文件读取\写入\复制内容——李帅醒博客
- Oracle查询优化--单表查询
- Oracle查询优化--排序
- Maven-使用及常见问题
- 蚯蚓
- Git-常用命令
- Js_闭包详解