【树分治】 BZOJ 2152 聪聪可可

考虑经过根的路径,不经过根的路径由分治得出。记子树中的所有点到根的路径长度对3取模以后为0的个数为a,为1的个数为b,为2的个数为c。。。。组合数学容易算出路径条数为a * a + b * c * 2。。。然后计算概率即可。。。

#include <iostream>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <climits>
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 20005
#define maxm 40005
#define eps 1e-7
#define mod 1000000007
#define INF 0x3f3f3f3f
#define PI (acos(-1.0))
#define lowbit(x) (x&(-x))
#define mp make_pair
#define ls o<<1
#define rs o<<1 | 1
#define lson o<<1, L, mid 
#define rson o<<1 | 1, mid+1, R
#define pii pair<int, int>
#pragma comment(linker, "/STACK:16777216")
typedef long long LL;
typedef unsigned long long ULL;
//typedef int LL;
using namespace std;
LL qpow(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base;base=base*base;b/=2;}return res;}
LL powmod(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base%mod;base=base*base%mod;b/=2;}return res;}
//head

struct Edge
{
	int v, w;
	Edge *next;
}*H[maxn], *edges, E[maxm];

bool done[maxn];
int size[maxn];
int mx[maxn];
vector<int> dis;
int n, root, ans, nsize;

void addedges(int u, int v, int w)
{
	edges->v = v;
	edges->w = w;
	edges->next = H[u];
	H[u] = edges++;
}

void init()
{
	edges = E;
	memset(H, 0, sizeof H);
	memset(done, 0, sizeof done);
}

void read()
{
	int u, v, w;
	for(int i = 1; i < n; i++) {
		scanf("%d%d%d", &u, &v, &w);
		addedges(u, v, w);
		addedges(v, u, w);
	}
}

void getroot(int u, int fa)
{
	size[u] = 1, mx[u] = 0;
	for(Edge *e = H[u]; e; e = e->next) if(!done[e->v] && e->v != fa) {
		int v = e->v;
		getroot(v, u);
		size[u] += size[v];
		mx[u] = max(mx[u], size[v]);
	}
	mx[u] = max(mx[u], nsize - size[u]);
	if(mx[u] < mx[root]) root = u;
}

void getdis(int u, int fa, int dist)
{
	dis.push_back(dist);
	for(Edge *e = H[u]; e; e = e->next) if(!done[e->v] && e->v != fa) {
		int v = e->v, w = e->w;
		getdis(v, u, dist + w);
	}
}

int calc(int u, int dist)
{
	dis.clear();
	getdis(u, 0, dist);
	int a = 0, b = 0, c = 0;
	for(int i = 0; i < dis.size(); i++) {
		if(dis[i] % 3 == 0) a++;
		if(dis[i] % 3 == 1) b++;
		if(dis[i] % 3 == 2) c++;
	}
	return a * a + b * c * 2;
}

void solve(int u)
{
	ans += calc(u, 0);
	done[u] = true;
	for(Edge *e = H[u]; e; e = e->next) if(!done[e->v]) {
		int v = e->v, w = e->w;
		ans -= calc(v, w);
		mx[0] = nsize = size[v];
		getroot(v, root = 0);
		solve(root);
	}
}

void work()
{
	ans = 0;
	mx[0] = nsize = n;
	getroot(1, root = 0);
	solve(root);
	int a = ans, b = n * n;
	int c = __gcd(a, b);
	a /= c, b /= c;
	printf("%d/%d\n", a, b);
}

int main()
{
	while(scanf("%d", &n)!=EOF) {
		init();
		read();
		work();
	}
	
	
	return 0;
}


你可能感兴趣的:(bzoj,树分治)