树中的最长路问题

树中的最长路

题目传送:hihoCoder - 1050 - 树中的最长路

AC代码:

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <cctype>
#include <cstdio>
#include <string>
#include <vector>
#include <complex>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <sstream>
#include <utility>
#include <iostream>
#include <algorithm>
#include <functional>
#define LL long long
#define INF 0x7fffffff
using namespace std;

int n;
const int maxn = 100005;
vector<int> G[maxn];

int vis[maxn];
int first[maxn];
int second[maxn];
int ans;

void dfs(int u) {
    vis[u] = 1;
    int d = G[u].size();
    int fi = 0, se = 0;
    int cnt = 0;//用于统计子树的个数
    priority_queue<int> que;//用优先队列来维护最大和次大,此优先队列默认为最大堆
    for(int i = 0; i < d; i ++) {
        int v = G[u][i];
        if(!vis[v]){
            cnt ++;
            dfs(v);
            que.push(first[v]);
        }
    }

    first[u] = second[u] = 0;
    if(cnt == 0) return;
    first[u] = que.top() + 1;
    que.pop();
    if(!que.empty()) second[u] = que.top() + 1;
    ans = max(ans, first[u] + second[u]);
    //cout << first[u] << " " << second[u] << endl;
}

int main() {
    scanf("%d", &n);
    int u, v;
    for(int i = 1; i < n; i ++) {
        scanf("%d %d", &u, &v);
        G[u].push_back(v);
        G[v].push_back(u);
    }
    ans = 0;
    memset(vis, 0, sizeof(vis));
    dfs(1);
    printf("%d\n", ans);
    return 0;
}

你可能感兴趣的:(树,ACM,最长路)