聪聪可可
作者:互联网
#include <iostream>
#include <cstdio>
using namespace std;
int read()
{
int x=0,f=1;
char c=getchar();
while(c<'0'||c>'9')
{
if(c=='-') f=-1;
c=getchar();
}
while(c>='0'&&c<='9')
{
x=x*10+c-'0';
c=getchar();
}
return f*x;
}
const int N=30000;
int root,size[N],sum,maxson[N],rem[N],num;
int had[N],to[N*2],len[N*2],nxt[N*2],p;
int n,a1,b1,c1,dis[N],x[3],y[3],ans,cnt,d;
bool f[N];
int gcd(int a,int b)
{
if(!b) return a;
return gcd(b,a%b);
}
void add(int x,int y,int z)
{
nxt[++p]=had[x];
to[p]=y;
len[p]=z;
had[x]=p;
}
void getroot(int u,int fa)
{
size[u]=1; maxson[u]=0;
for(int i=had[u];i;i=nxt[i])
{
int v=to[i];
if(v==fa||f[v]) continue;
getroot(v,u);
size[u]+=size[v];
maxson[u]=max(maxson[u],size[v]);
}
maxson[u]=max(maxson[u],sum-size[u]);
if(maxson[u]<maxson[root]) root=u;
}
void getdis(int u,int fa)
{
rem[++num]=dis[u]%3;
for(int i=had[u];i;i=nxt[i])
{
int v=to[i];
if(v==fa||f[v]) continue;
dis[v]=dis[u]+len[i];
getdis(v,u);
}
}
void solve(int u)
{
x[0]=1; x[1]=x[2]=0;
for(int i=had[u];i;i=nxt[i])
{
int v=to[i];
if(f[v]) continue;
y[0]=y[1]=y[2]=0;
num=0; dis[v]=len[i];
getdis(v,u);
for(int i=1;i<=num;i++) y[rem[i]]++;
ans+=(x[0]*y[0]+x[1]*y[2]+x[2]*y[1])*2;
x[0]+=y[0]; x[1]+=y[1]; x[2]+=y[2];
}
}
void divide(int u)
{
f[u]=1; solve(u);
for(int i=had[u];i;i=nxt[i])
{
int v=to[i];
if(f[v]) continue;
sum=size[v]; root=0;
getroot(v,0); divide(root);
}
}
int main()
{
n=read(); cnt=n*n; ans+=n;
for(int i=1;i<n;i++)
{
a1=read(); b1=read(); c1=read();
add(a1,b1,c1); add(b1,a1,c1);
}
maxson[root]=sum=n;
getroot(1,0); divide(root);
d=gcd(ans,cnt);
cout<<ans/d<<"/"<<cnt/d;
return 0;
}
标签:可可,std,&&,int,while,聪聪,include,getchar 来源: https://blog.csdn.net/qq_42192786/article/details/89920388