DFS
题目没读懂想了半天。。。
超级大水题
对每个节点记录一个size,然后枚举每一条边,答案就是边权 ×(size[1]−2∗size[v]) × ( s i z e [ 1 ] − 2 ∗ s i z e [ v ] )
size的话。。。dfs喽
代码:
#include<cctype>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 1000005
#define F inline
using namespace std;
typedef long long LL;
struct edge{ int next,to,dis; }ed[N<<1];
int n,k,h[N],sz[N],fa[N];
F char readc(){
static char buf[100000],*l=buf,*r=buf;
if (l==r) r=(l=buf)+fread(buf,1,100000,stdin);
if (l==r) return EOF; return *l++;
}
F int _read(){
int x=0,f=1; char ch=readc();
while (!isdigit(ch)) { if (ch=='-') f=-1; ch=readc(); }
while (isdigit(ch)) x=(x<<3)+(x<<1)+(ch^48),ch=readc();
return x*f;
}
#define addedge(x,y,z) (ed[++k]=(edge){h[x],(y),(z)},h[x]=k)
#define abs(x) (((x)<0)?-(x):(x))
void dfs(int x){
sz[x]=1;
for (int i=h[x],v;i;i=ed[i].next)
if ((v=ed[i].to)!=fa[x])
fa[v]=x,dfs(v),sz[x]+=sz[v];
}
int main(){
n=_read();
for (int i=1,x,y,z;i<n;i++){
x=_read(),y=_read(),z=_read();
addedge(x,y,z);addedge(y,x,z);
}
dfs(1); LL ans=0;
for (int x=1;x<=n;x++)
for (int i=h[x],v;i;i=ed[i].next)
if ((v=ed[i].to)!=fa[x])
ans+=1ll*ed[i].dis*abs(sz[1]-(sz[v]<<1));
return printf("%lld\n",ans),0;
}