标签:ace void def names get 分治 ++i i++ pre
#include <cstdio>
#include <algorithm>
using namespace std;
#define N 100010
int head[N],to[N<<1],val[N<<1],nxt[N<<1];
int mx[N],size[N],n,all,idx,root,fa[N]; bool vis[N];
void add(int a,int b,int c)
{nxt[++idx]=head[a],to[idx]=b,val[idx]=c,head[a]=idx;}
void getroot(int p,int from)
{
mx[p]=0,size[p]=1;
for(int i=head[p];i;i=nxt[i])
if(to[i]!=from&&(!vis[to[i]])) getroot(to[i],p),
size[p]+=size[to[i]],mx[p]=max(mx[p],size[to[i]]);
mx[p]=max(all-size[p],mx[p]);
if(mx[root]>mx[p]) root=p;
}
void getsize(int p,int from)
{
size[p]=1;
for(int i=head[p];i;i=nxt[i]) if(to[i]!=from&&(!vis[to[i]]))
getsize(to[i],p),size[p]+=size[to[i]];
}
void dfs2(int p)
{
vis[p]=true,getsize(p,0);
for(int i=head[p];i;i=nxt[i]) if(!vis[to[i]])
all=size[to[i]],root=0,getroot(to[i],0),fa[root]=p,dfs2(root);
}
int main()
{
scanf("%d",&n);
for(int i=1,x,y,z;i<n;i++)
scanf("%d%d%d",&x,&y,&z),add(x,y,z),add(y,x,z);
root=0,mx[0]=n+1,all=n,getroot(1,0),dfs2(root);
}
标签:ace void def names get 分治 ++i i++ pre
原文地址:https://www.cnblogs.com/yangsongyi/p/10658064.html