传送门:http://www.lydsy.com/JudgeOnline/problem.php?id=2152
题意:求树上任意两点(两点可以相同)路径长度%3 == 0 的方案数
思路:关于树上路径统计方案 首先就想(tao)到(lu)树分治
code:
//统计树上路径的方案数目
#include<bits/stdc++.h>
using namespace std;
const int maxn = 20100;
struct EDGE
{
int to, next, len;
} edge[maxn << 1];
int head[maxn], clk;
int n, k;
int vis[maxn], ans, root, num;
void init()
{
clk = 0;
memset(head, -1, sizeof(head));
}
void add(int a, int b, int len)
{
edge[clk].to = b;
edge[clk].len = len;
edge[clk].next = head[a];
head[a] = clk++;
}
int maxson[maxn], size[maxn], mi, dis[maxn];
void dfs_size(int u, int fa) //子树大小
{
size[u] = 1;
maxson[u] = 0;
for(int i = head[u]; i != -1; i = edge[i].next)
{
int son = edge[i].to;
if(son == fa || vis[son] == 1) continue;
dfs_size(son, u);
size[u] += size[son];
if(size[son] > maxson[u]) maxson[u] = size[son];
}
}
void dfs_root(int r, int u, int fa) //根据子树大小求重心
{
if(size[r] - size[u] > size[r] / 2) return;
if(maxson[u] <= size[r] / 2)
{
root = u;
return;
}
for(int i = head[u]; i != -1; i = edge[i].next)
{
int son = edge[i].to;
if(son == fa || vis[son] == 1) continue;
dfs_root(r, son, u);
}
}
void dfs_dis(int u, int d, int fa) //求距离
{
d%=3;
dis[num++] = d;
for(int i = head[u]; i != -1; i = edge[i].next)
{
int son = edge[i].to;
if(son == fa || vis[son] == 1) continue;
dfs_dis(son, d + edge[i].len, u);
}
}
int calc(int u, int d)
{
int ret = 0;
num = 0;
dfs_dis(u, d, 0);
int dp[10]={0,0,0,0,0,0,0,0,0,0};
for(int i=0;i<num;i++)
{
dis[i]%=3;
ret+=dp[(3-dis[i])%3];
dp[dis[i]%3]+=1;
}
return ret;
}
void dfs(int u)
{
dfs_size(u, 0);
dfs_root(u, u, 0);
ans += calc(root, 0);
vis[root] = 1;
for(int i = head[root]; i != -1; i = edge[i].next)
{
int son = edge[i].to;
if(vis[son] == 1) continue;
ans -= calc(son, edge[i].len);
dfs(son);
}
}
int main()
{
while(scanf("%d", &n) != EOF)
{
init();
memset(vis, 0, sizeof(vis));
for(int i = 1; i <= n-1; i++)
{
int a, b, len;
scanf("%d%d%d", &a, &b, &len);
len%=3;
add(a, b, len);
add(b, a, len);
}
ans = 0;
dfs(1);
ans=ans*2+n;
int k=__gcd(ans,n*n);
printf("%d/%d\n", ans/k,n*n/k);
}
return 0;
}