[bzoj3124] [Sdoi2013]直径
看了child学长的题解才知道怎么写TAT
http://www.cnblogs.com/ctlchild/p/5160272.html
以前不知道直径都是过重心的。。代码改着改着就和标程完全一样了QAQ
1 #include<cstdio> 2 #include<iostream> 3 #include<cstring> 4 #define ll long long 5 using namespace std; 6 const int maxn=200033; 7 struct zs{ 8 int too,pre,dis; 9 }e[maxn<<1];int tot,last[maxn]; 10 int sz[maxn],fa[maxn],mx[maxn],bel[maxn],dep[maxn]; 11 ll dis[2][maxn],len; 12 int rt,st1[maxn],st2[maxn],top1,top2; 13 int i,j,k,n,m,a,b; 14 15 int ra;char rx; 16 inline int read(){ 17 rx=getchar(),ra=0; 18 while(rx<'0'||rx>'9')rx=getchar(); 19 while(rx>='0'&&rx<='9')ra*=10,ra+=rx-48,rx=getchar();return ra; 20 } 21 inline int max(int a,int b){return a>b?a:b;} 22 23 inline void insert(int a,int b,int c){ 24 e[++tot].too=b,e[tot].dis=c,e[tot].pre=last[a],last[a]=tot; 25 e[++tot].too=a,e[tot].dis=c,e[tot].pre=last[b],last[b]=tot; 26 } 27 inline void dfs(int x,int id){ 28 sz[x]=1;mx[x]=0;dep[x]=dep[fa[x]]+1; 29 for(register int i=last[x];i;i=e[i].pre)if(e[i].too!=fa[x]) 30 dis[id][e[i].too]=e[i].dis+dis[id][x],fa[e[i].too]=x, 31 dfs(e[i].too,id), 32 sz[x]+=sz[e[i].too],mx[x]=max(mx[x],sz[e[i].too]); 33 mx[x]=max(mx[x],n-sz[x]); 34 } 35 inline void dfs1(int x){ 36 dep[x]=dep[fa[x]]+1; 37 for(register int i=last[x];i;i=e[i].pre)if(e[i].too!=fa[x]) 38 fa[e[i].too]=x,dfs1(e[i].too); 39 } 40 inline void dfs2(int x,int chain){ 41 register int i,pos=0;bel[x]=chain; 42 for(i=last[x];i;i=e[i].pre)if(e[i].too!=fa[x]&&sz[e[i].too]>sz[pos])pos=e[i].too; 43 if(!pos)return; 44 dfs2(pos,chain); 45 for(i=last[x];i;i=e[i].pre)if(e[i].too!=fa[x]&&e[i].too!=pos)dfs2(e[i].too,e[i].too); 46 } 47 inline int getlca(int a,int b){ 48 while(bel[a]!=bel[b]){ 49 if(dep[bel[a]]<dep[bel[b]])swap(a,b); 50 a=fa[bel[a]]; 51 } 52 return dep[a]<dep[b]?a:b; 53 } 54 int main(){ 55 register int i; 56 n=read(); 57 for(i=1;i<n;i++)a=read(),b=read(),insert(a,b,read()); 58 int s,t; 59 fa[1]=0,dfs(1,0);for(i=2,s=1;i<=n;i++)if(dis[0][i]>dis[0][s])s=i; 60 fa[s]=0,dfs(s,1);for(i=2,t=1;i<=n;i++)if(dis[1][i]>dis[1][t])t=i; 61 len=dis[1][t];printf("%lld\n",len); 62 fa[t]=0,dis[0][t]=0, 63 dfs(t,0); 64 for(i=1;i<=n;i++){ 65 if(dis[0][i]==len&&dis[1][i]==len){puts("0");return 0;} 66 if(dis[0][i]==len)st1[++top1]=i; 67 if(dis[1][i]==len)st2[++top2]=i; 68 } 69 for(i=rt=1;i<=n;i++)if(mx[i]<mx[rt])rt=i; 70 fa[rt]=0,dfs1(rt);dfs2(rt,rt); 71 for(a=st1[1],i=2;i<=top1&&a!=rt;i++)a=getlca(a,st1[i]); 72 for(b=st2[1],i=2;i<=top2&&b!=rt;i++)b=getlca(b,st2[i]); 73 printf("%d\n",dep[a]+dep[b]-dep[getlca(a,b)]*2); 74 return 0; 75 }