Analysis
这道题的方向没有任何用……不用管
然后就是一个模板题了
求树的直径
两遍dfs(或bfs),或者是树形dp(维护最大值和次大值)
Code
两遍dfs
#include<cstdio>
#include<cstring>
#include<cmath>
#define in read()
#define N 40009
#define M 80009
using namespace std;
inline int read(){
char ch;int f=1,res=0;
while((ch=getchar())<'0'||ch>'9') if(ch=='-') f=-1;
while(ch>='0'&&ch<='9'){
res=(res<<3)+(res<<1)+ch-'0';
ch=getchar();
}
return f==1?res:-res;
}
int n,m,ans=0,p,d[N];
int nxt[M],to[M],head[N],w[M],ecnt=0;
char st[100];
inline void add(int x,int y,int z){
nxt[++ecnt]=head[x];head[x]=ecnt;to[ecnt]=y;w[ecnt]=z;
}
void dfs(int u,int fu){
if(ans<d[u]){ans=d[u];p=u;}
for(int e=head[u];e;e=nxt[e]){
int v=to[e];
if(v==fu) continue;
d[v]=d[u]+w[e];
dfs(v,u);
}
}
void find(int x){
ans=0;
d[x]=0;
dfs(x,0);
}
int main(){
n=in;m=in;
int i,j,k,x,y,z;
for(i=1;i<=m;++i){
x=in;y=in;z=in;scanf("%s",st);
add(x,y,z);add(y,x,z);
}
find(1);
find(p);
printf("%d",ans);
return 0;
}
树形dp
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define in read()
#define N 40009
#define M 80009
using namespace std;
inline int read(){
char ch;int f=1,res=0;
while((ch=getchar())<'0'||ch>'9') if(ch=='-') f=-1;
while(ch>='0'&&ch<='9'){
res=(res<<3)+(res<<1)+ch-'0';
ch=getchar();
}
return f==1?res:-res;
}
int n,m,ans=0,p;
int nxt[M],to[M],head[N],w[M],ecnt=0;
int f1[N],f2[N];
char st[100];
inline void add(int x,int y,int z){
nxt[++ecnt]=head[x];head[x]=ecnt;to[ecnt]=y;w[ecnt]=z;
}
void dfs(int u,int fu){
for(int e=head[u];e;e=nxt[e]){
int v=to[e];
if(v==fu) continue;
dfs(v,u);
if(f1[u]<f1[v]+w[e]){f2[u]=f1[u],f1[u]=f1[v]+w[e];}
else if(f2[u]<f1[v]+w[e]) f2[u]=f1[v]+w[e];
ans=max(ans,f1[u]+f2[u]);
}
}
int main(){
n=in;m=in;
int i,j,k,x,y,z;
for(i=1;i<=m;++i){
x=in;y=in;z=in;scanf("%s",st);
add(x,y,z);add(y,x,z);
}
dfs(1,0);
printf("%d",ans);
return 0;
}