题意:中文题面
分析:放官方题解,就是从1为根节点深搜记录节点的深度,选出最大的深度的点,将该到达该点的节点都vis掉,然后再重新计算没有vis的点的深度,找最大的相加就是答案。放张图好理解:
收获:计算树的节点的深度
代码:
/************************************************ * Author :Running_Time * Created Time :2015-8-31 14:03:09 * File Name :B.cpp ************************************************/ #include <cstdio> #include <algorithm> #include <iostream> #include <sstream> #include <cstring> #include <cmath> #include <string> #include <vector> #include <queue> #include <deque> #include <stack> #include <list> #include <map> #include <set> #include <bitset> #include <cstdlib> #include <ctime> using namespace std; #define lson l, mid, rt << 1 #define rson mid + 1, r, rt << 1 | 1 typedef long long ll; const int N = 1e5 + 10; const int INF = 0x3f3f3f3f; const int MOD = 1e9 + 7; int dep[N]; bool vis[N]; vector<int> G[N]; int fa[N]; void DFS(int u, int d) { dep[u] = d; for (int v, i=0; i<G[u].size (); ++i) { v = G[u][i]; if (vis[v]) continue; fa[v] = u; DFS (v, d + 1); } } int main(void) { int n; scanf ("%d", &n); for (int u, v, i=1; i<n; ++i) { scanf ("%d%d", &u, &v); G[u].push_back (v); } fa[1] = 0; DFS (1, 0); int mx = 0, id = 0; for (int i=1; i<=n; ++i) { if (mx < dep[i]) { mx = dep[i]; id = i; } } int ans = mx; while (id) { vis[id] = true; id = fa[id]; } for (int i=1; i<=n; ++i) { if (vis[i]) { DFS (i, 0); } } mx = 0; for (int i=1; i<=n; ++i) { if (!vis[i]) mx = max (mx, dep[i]); } printf ("%d\n", ans + mx); return 0; }
时间: 2024-10-28 08:00:51