bzoj2152

时间:2022-09-13 15:52:16

题解:

  随便点分治,用一个t数组,t[i]代表有u到root的值mod3==i; 那么答案就是:t[0]*t[0]+t[1]*t[2]*2;

代码:

  

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#define N 20005
using namespace std;
int pre[N*],now[N],v[N*],val[N*];
int d[N],son[N],f[N];
int t[];
bool vis[N];
int tot,all,n,ans,root;
int read()
{
int x=; char ch; bool bo=;
while (ch=getchar(), ch<''||ch>'') if (ch=='-') bo=;
while (x=x*+ch-'',ch=getchar(),ch>=''&&ch<='');
if (bo) return -x; return x;
}
void ins(int a,int b,int c)
{
++tot; pre[tot]=now[a]; now[a]=tot; v[tot]=b; val[tot]=c;
}
int gcd(int a,int b)
{
return b==?a:gcd(b,a%b);
}
void getroot(int u,int fa)
{
son[u]=; f[u]=;
for (int p=now[u]; p; p=pre[p])
{
int vv=v[p];
if (vv==fa || vis[vv]) continue;
getroot(vv,u); son[u]+=son[vv];
f[u]=max(f[u],son[vv]);
}
f[u]=max(f[u],all-son[u]);
if (f[u]<f[root]) root=u;
}
void getarray(int u,int fa)
{
t[d[u]]++;
for (int p=now[u]; p; p=pre[p])
{
int vv=v[p];
if (vv==fa||vis[vv]) continue;
d[vv]=(d[u]+val[p])%;
getarray(vv,u);
}
}
int calc(int u,int value)
{
t[]=t[]=t[]=; d[u]=value;
getarray(u,);
return t[]*t[]+t[]*t[]*;
}
void solve(int u)
{
ans+=calc(u,); vis[u]=;
for (int p=now[u]; p; p=pre[p])
{
int vv=v[p];
if (vis[vv]) continue;
ans-=calc(vv,val[p]);
root=; all=son[vv];
getroot(vv,);
solve(root);
}
}
int main()
{
n=read();
for (int i=; i<n; i++)
{
int a=read(),b=read(),val=read()%;
ins(a,b,val); ins(b,a,val);
}
ans=;
f[root=]=all=n; getroot(,);
solve(root);
int kk=gcd(ans,n*n);
printf("%d/%d\n",ans/kk,n*n/kk);
}