SPOJ_PT07Z 树最长路径问题

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 3

Output:
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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值