zoukankan      html  css  js  c++  java
  • hihoCoder week11 树中的最长路

    题目链接: https://hihocoder.com/contest/hiho11/problem/1

    求树中节点对 距离最远的长度

    #include <bits/stdc++.h>
    using namespace std;
    
    const int N = 1e5 + 10;
    int n;
    vector<int> G[N];
    int d[N];
    void dfs(int u, int fa)
    {
        for(int i=0; i<G[u].size(); i++) {
            int v = G[u][i];
            if(v != fa) {
                d[v] = d[u] + 1;
                dfs(v, u);
            }
        }
    }
    
    int main()
    {
        freopen("in.txt", "r", stdin);
        scanf("%d",&n);
        for(int i=0; i<n-1; i++) {
            int a,b; scanf("%d %d", &a, &b);
            G[a].push_back(b);
            G[b].push_back(a);
        }
        d[1] = 0;
        dfs(1, 0);
        int mx =  0;
        int index = -1;
        for(int i=1; i<=n; i++) {
            if(mx < d[i]) {
                mx = d[i];
                index = i;
            }
        }
        //printf("%d
    ", mx);   
        memset(d,0,sizeof(d));
        dfs(index, 0);
        for(int i=1; i<=n; i++) {
            if(mx < d[i]) {
                mx = d[i];
                index = i;
            }
        }
        cout << mx <<endl;                                                                                     
        return 0;
    }
    #include <bits/stdc++.h>
    using namespace std;
    
    const int N = 1e5 + 10;
    vector<int> G[N];
    int n, ans;
    
    int dfs(int u,int fa)
    {
        int l1=-1,l2=-1;
        for(int i=0; i<G[u].size(); i++) {
            int v = G[u][i]; 
            if(v == fa) continue;
            int l = dfs(v, u);
            if(l > l1) 
                l2=l1 , l1=l;
            else 
                l2 = max(l2, l);
            
        }
        //cout << u <<" "<< l1 <<" "<< l2 <<endl;
        ans = max(ans , l1 + l2 + 2);
        // cout << u <<" 最长的路为" <<l1 <<endl;
        return l1+1;
    }
    
    
    int main()
    {
        //freopen("in.txt", "r", stdin);
        cin >> n;
        for(int i=1; i<n; i++) {
            int a,b; scanf("%d %d", &a, &b);
            G[a].push_back(b);
            G[b].push_back(a);
        }
        ans = 0;
        dfs(1,0);
        cout << ans <<endl;
        return 0;
    }
  • 相关阅读:
    Volume 6. Mathematical Concepts and Methods
    git帮助网址
    ubuntu 下安装wine
    ubuntu 通过ppa源安装mysql5.6
    ubuntu qq安装
    ubuntu14.04 fcitx安装
    language support图标消失
    ubuntu root用户登陆
    ubuntu 安装codeblocks13.12
    ubuntu tomcat自启动
  • 原文地址:https://www.cnblogs.com/Draymonder/p/9977514.html
Copyright © 2011-2022 走看看