1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| #include<cstdio> #include<cstring> #include<algorithm> #define re register using namespace std; const int MAXn = 5e5; const int MAXm = MAXn; const int FINF = 0xc0c0c0c0;
int n; int head[MAXn + 10], cntnex, nex[MAXm * 2 + 10], to[MAXm * 2 + 10], wei[MAXm * 2 + 10]; void Insert(int u, int v, int w) { nex[++cntnex] = head[u]; head[u] = cntnex; to[cntnex] = v; wei[cntnex] = w; }
int dis[MAXn + 10]; bool vis[MAXn + 10]; void Dfs(int cur) { vis[cur] = 1; for (re int i = head[cur]; i; i = nex[i]) { if (vis[to[i]]) continue; dis[to[i]] = dis[cur] + wei[i]; Dfs(to[i]); } } int EvaFar(int root) { memset(dis, 0xc0, sizeof(dis)); memset(vis, 0, sizeof(vis)); dis[root] = 0; Dfs(root); int mx = FINF, maxer = 0; for (re int i = 1; i <= n; ++i) { if (mx < dis[i]) { mx = dis[i]; maxer = i; } } return maxer; }
int side1, side2; int main() { scanf("%d", &n); for (re int i = 1, u, v, w; i < n; ++i) { scanf("%d %d %d", &u, &v, &w); Insert(u, v, w); Insert(v, u, w); } side1 = EvaFar(1); side2 = EvaFar(side1); printf("%d %d\n", side1, side2); printf("%d\n", dis[side2]); }
|