# bzoj3124: [Sdoi2013]直径

2020-12-07 14:26:09

``````#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<queue>
using namespace std;
typedef long long ll;
struct node {

int x,y,next;ll d;}a[510000];int len,last[210000];
void ins(int x,int y,ll d) {len++;a[len].x=x;a[len].y=y;a[len].d=d;a[len].next=last[x];last[x]=len;}
int G,fa[210000],bian[210000];ll D;
void dfs(int x,ll d,int f) {
if(D<d) {D=d;G=x;}
for(int k=last[x];k;k=a[k].next) {
int y=a[k].y;
if(y!=f){fa[y]=x;bian[y]=k;dfs(y,d+a[k].d,x);}
}
}
int s[210000];
ll T;bool v[210000];
void dfs1(int x,ll d,int f) {
if(T<d)T=d;
for(int k=last[x];k;k=a[k].next) {
int y=a[k].y;
if(v[y]==true&&y!=f) dfs1(y,d+a[k].d,x);
}
}
int ans;
void dfs2(int x,int d,int f,int ed) {
if(x==ed){ans=d;return ;}
for(int k=last[x];k;k=a[k].next) {
int y=a[k].y;
if(y!=f) dfs2(y,d+1,x,ed);
}
}
int main() {
int n;scanf("%d",&n);len=0;memset(last,0,sizeof(last));
for(int i=1;i<n;i++) {
int x,y;ll d;scanf("%d%d%lld",&x,&y,&d);
ins(x,y,d);ins(y,x,d);
}
int X,Y;
memset(bian,0,sizeof(bian));dfs(1,0,0);X=G;D=0;dfs(X,0,0);Y=G;
int x=Y,slen=0;memset(v,true,sizeof(v));
while(x!=X) {s[++slen]=x;v[x]=false;x=fa[x];}
s[++slen]=X;v[X]=false;
int ansx=Y;ll K=a[bian[s[1]]].d;
for(int i=2;i<=slen;i++) {
T=0;dfs1(s[i],0,0);
if(T==K)ansx=s[i];K+=a[bian[s[i]]].d;
}
for(int i=slen;i>=2;i--) bian[s[i]]=bian[s[i-1]];bian[s[1]]=0;
int ansy=X;K=a[bian[s[slen]]].d;
for(int i=slen-1;i>=1;i--) {
T=0;dfs1(s[i],0,0);
if(T==K)ansy=s[i];K+=a[bian[s[i]]].d;
}dfs2(ansx,0,0,ansy);printf("%lld\n%d\n",D,ans);
return 0;
}``````

https://my.oschina.net/u/4382844/blog/4778620