vector求数的直径
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 9;
int n;
struct Edge
{
int id, w;
};
vector<Edge> h[N];
int dist[N];
void dfs(int u, int father, int distance)
{
dist[u] = distance;
for(auto node : h[u])
if(node.id != father)
dfs(node.id, u, distance + node.w);
}
int main()
{
scanf("%d", &n);
for(int i = 0; i < n; i ++)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
h[a].push_back({b, c});
h[b].push_back({a, c});
}
dfs(1, -1, 0);
int u = 1;
for(int i = 1; i <= n; i ++)
if(dist[i] > dist[u])
u = i ;
dfs(u, -1, 0);
for(int i = 1; i <= n; i ++)
if(dist[i] > dist[u])
u = i;
int s = dist[u];
printf("%lld\n", s * 10 + s * (s + 1ll) / 2);
return 0;
}
链式前向星求树的直径(数组模拟邻接表)
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 9, M = 2e5 + 9;
int n;
int h[N], e[M], w[M], ne[M], idx;
int dist[N];
void add(int a, int b, int c)
{
e[idx] = b,
w[idx] = c;
ne[idx] = h[a];
h[a] = idx ++ ;
}
void dfs(int u, int father, int distance)
{
dist[u] = distance;
for(int i = h[u]; ~i; i = ne[i])
{
int j = e[i];
if(j != father)
dfs(j, u, distance + w[i]);
}
}
int main()
{
scanf("%d", &n);
memset(h, -1, sizeof h);
for(int i = 0; i < n; i ++)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(a, b, c), add(b, a, c);
}
dfs(1, -1, 0);
int u = 1;
for(int i = 2; i <= n; i ++)
if(dist[u] < dist[i])
u = i;
dfs(u, -1, 0);
for(int i = 1; i <= n; i ++)
if(dist[u] < dist[i])
u = i;
printf("%lld\n", dist[u] * 10 + (dist[u] + 1ll ) * dist[u] / 2);
return 0;
}