题目链接
寻找这样的任意两个点(分前后),让他们两个的距离是3的倍数,这时候,询问有多少个这样的对,并且输出概率,概率要求是最简分数形式。
然后一开始的时候,我仿照之前的这一份点分治模板,然后因为在solve判断分治区间上的点的询问是的,其中line是指边的个数,这时候就会把复杂度拉的很高了,所以必须去进行优化。
这时候,我们考虑3的倍数会被怎样组成?(1+2)、(0+0)、(2+1),是不是一般由两个点只能有这两种组成方式,然后我们只需要存下来到该点距离为0、1、2(%3)时候的点的个数即可,最后直接返回答案:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define INF 0x3f3f3f3f
#define efs 1e-6
#define HalF (l + r)>>1
#define lsn rt<<1
#define rsn rt<<1|1
#define Lson lsn, l, mid
#define Rson rsn, mid+1, r
#define QL Lson, ql, qr
#define QR Rson, ql, qr
#define myself rt, l, r
using namespace std;
typedef double lb;
typedef unsigned long long ull;
typedef long long ll;
int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
const int maxN = 2e4 + 7;
int N, M, K, rt, mx, cnt, head[maxN], siz[maxN], son[maxN], all, ans;
bool vis[maxN];
struct Eddge
{
int nex, to, val;
Eddge(int a=-1, int b=0, int c=0):nex(a), to(b), val(c) {}
}edge[maxN<<1];
inline void addEddge(int u, int v, int w) { edge[cnt] = Eddge(head[u], v, w); head[u] = cnt++; }
inline void add(int u, int v, int w) { addEddge(u, v, w); addEddge(v, u, w); }
void findrt(int u, int fa)
{
siz[u] = 1; son[u] = 0;
for(int i=head[u], v; ~i; i=edge[i].nex)
{
v = edge[i].to;
if(vis[v] || v == fa) continue;
findrt(v, u);
siz[u] += siz[v];
son[u] = max(son[u], siz[v]);
}
son[u] = max(son[u], all - siz[u]);
if(son[u] < mx) { mx = son[u]; rt = u; }
}
int Stop, Stap[maxN], sum[3];
void query(int u, int fa, int dis)
{
sum[dis % 3]++;
for(int i=head[u], v; ~i; i=edge[i].nex)
{
v = edge[i].to;
if(vis[v] || v == fa) continue;
query(v, u, dis + edge[i].val);
}
}
inline int solve(int root, int dis)
{
memset(sum, 0, sizeof(sum));
query(root, 0, dis);
return sum[1] * sum[2] * 2 + sum[0] * sum[0];
}
void divide(int u)
{
ans += solve(u, 0); vis[u] = true;
int totsiz = all;
for(int i=head[u], v; ~i; i=edge[i].nex)
{
v = edge[i].to;
if(vis[v]) continue;
ans -= solve(v, edge[i].val);
mx = INF; rt = 0;
all = siz[v] > siz[u] ? totsiz - siz[u] : siz[v];
findrt(v, 0);
divide(rt);
}
}
inline void init()
{
cnt = ans = 0;
memset(sum, 0, sizeof(sum));
for(int i=1; i<=N; i++) head[i] = -1;
for(int i=1; i<=N; i++) vis[i] = false;
rt = 0; mx = INF; all = N;
}
int main()
{
scanf("%d", &N);
init();
for(int i=1, u, v, w; i<N; i++)
{
scanf("%d%d%d", &u, &v, &w);
add(u, v, w);
}
findrt(1, 0);
divide(rt);
int tmp = N * N;
int _GCD = gcd(ans, tmp);
printf("%d/%d\n", ans / _GCD, tmp / _GCD);
return 0;
}