bfs
点击查看代码
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
#define LL long long
int cnt,h[N],to[N*2],w[N*2],ne[N*2];
void add(int a,int b,int c){
ne[++cnt]=h[a];
w[cnt]=c;
to[cnt]=b;
h[a]=cnt;
}
LL d[N],mx,vis[N];
void bfs(int x){
memset(d,0,sizeof d);
memset(vis,0,sizeof vis);
queue<LL> q;
q.push(x);
while(q.size()){
LL t=q.front();
q.pop();
if(vis[t]) continue;
vis[t]=1;
for(int i=h[t];i;i=ne[i]){
int w1=w[i],v=to[i];
if(d[v]<d[t]+w1&&!vis[v]){
d[v]=d[t]+w1;
if(d[v]>d[mx]) mx=v;
q.push(v);
}
}
}
}
int main(){
int n;
LL ans=0;
cin>>n;
for(int i=1;i<n;i++){
int a,b,c;
cin>>a>>b>>c;
ans+=1LL*c*2;
add(a,b,c);
add(b,a,c);
}
bfs(1);
bfs(mx);
ans-=d[mx];
cout<<ans;
return 0;
}
点击查看代码
const int N = 10000 + 10;
int n, d = 0;
int d1[N], d2[N];
vector<int> E[N];
void dfs(int u, int fa) {
d1[u] = d2[u] = 0;
for (int v : E[u]) {
if (v == fa) continue;
dfs(v, u);
int t = d1[v] + 1;
if (t > d1[u])
d2[u] = d1[u], d1[u] = t;
else if (t > d2[u])
d2[u] = t;
}
d = max(d, d1[u] + d2[u]);
}
int main() {
scanf("%d", &n);
for (int i = 1; i < n; i++) {
int u, v;
scanf("%d %d", &u, &v);
E[u].push_back(v), E[v].push_back(u);
}
dfs(1, 0);
printf("%d\n", d);
return 0;
}