13/25
【样例说明】
13组点对分别是(1,1) (2,2) (2,3) (2,5) (3,2) (3,3) (3,4) (3,5) (4,3) (4,4) (5,2) (5,3) (5,5)。
【数据规模】
对于100%的数据,n<=20000。
简单的树分治,不过也可以直接树上dp解决。
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef unsigned long long LL;
const int INF = 0x7FFFFFFF;
const int mod = 1e9 + 7;
const int maxn = 1e5 + 10;
int n, m, x, y, z;
int ft[maxn], nt[maxn], u[maxn], v[maxn], sz;
int vis[maxn], cnt[maxn], mx[maxn], dis[maxn], tot;
void AddEdge(int x, int y, int z)
{
u[sz] = y; v[sz] = z; nt[sz] = ft[x]; ft[x] = sz++;
}
void clear(int x)
{
sz = 0; mx[0] = INF;
for (int i = 1; i <= x; i++)
{
ft[i] = -1; vis[i] = 0;
}
}
int dfs(int x, int fa, int sum)
{
int ans = 0;
cnt[x] = 1; mx[x] = 0;
for (int i = ft[x]; i != -1; i = nt[i])
{
if (u[i] == fa || vis[u[i]]) continue;
int k = dfs(u[i], x, sum);
cnt[x] += cnt[u[i]];
mx[x] = max(mx[x], cnt[u[i]]);
if (mx[k] < mx[ans]) ans = k;
}
mx[x] = max(mx[x], sum - cnt[x]);
return mx[x] < mx[ans] ? x : ans;
}
void dfsdis(int x, int fa, int len)
{
++dis[len % 3];
for (int i = ft[x]; i != -1; i = nt[i])
{
if (vis[u[i]] || u[i] == fa) continue;
dfsdis(u[i], x, (len + v[i]) % 3);
}
}
int find(int x, int len)
{
for (int i = 0; i < 3; i++) dis[i] = 0;
dfsdis(x, -1, len);
return dis[0] * dis[0] + 2 * dis[1] * dis[2];
}
int solve(int x, int sum)
{
int y = dfs(x, -1, sum), ans = find(y, 0);
vis[y] = 1;
for (int i = ft[y]; i != -1; i = nt[i])
{
if (!vis[u[i]])
{
ans -= find(u[i], v[i]);
if (cnt[u[i]] < cnt[y]) ans += solve(u[i], cnt[u[i]]);
else ans += solve(u[i], sum - cnt[y]);
}
}
return ans;
}
int gcd(int x, int y)
{
return x%y ? gcd(y, x%y) : y;
}
int main()
{
while (scanf("%d", &n) != EOF)
{
clear(n);
for (int i = 1; i < n; i++)
{
scanf("%d%d%d", &x, &y, &z);
AddEdge(x, y, z);
AddEdge(y, x, z);
}
x = solve(1, n); y = n*n; z = gcd(x, y);
printf("%d/%d\n", x / z, y / z);
}
return 0;
}