[BZOJ2152] [国家集训队] 聪聪可可 [树形dp]

题意:
给出一个 N N 个点的树,每条边上有权值 w i w_i
3 ( u , v ) \frac{路径上权值和为3的倍数的有序对(u,v)数}{总有序对数}

分母好搞,考虑怎么求分子。
显然可以把路径上边权和对 3 3 取模,结果为 0 0 的就是合法路径。
不过路径的问题得分解为 d i s ( u ) + d i s ( v ) 2 d i s ( l c a ) dis(u)+dis(v)-2*dis(lca)
考虑对于某个点,路径过该点的点对数
c n t ( d i s % 3 = = 1 ) c n t ( d i s % 3 = = 2 ) 2 + c n t 2 ( 3 d i s ) cnt(dis\%3==1)*cnt(dis\%3==2)*2+cnt^2(3|dis)
当然这是不对的,因为 l c a ( u , v ) lca(u,v) 不一定就是这个点
显然,如果要 l c a = r o o t lca=root 那么 ( u , v ) (u,v) 应该分别在以 r o o t root 不同的子节点为根的子树中
只需要记录前面子树的结果跟当前子树的结果搞一下就好了
f ( x , r ) f(x,r) 表示点 x x 为根的子树中到 x x 路径权值和 % 3 = r \%3=r 的点数
Θ ( N ) \Theta(N)

注意 u u 可以 = v =v

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<cctype>
using namespace std;
#define add_edge(u,v,w) nxt[++tot]=head[u],head[u]=tot,to[tot]=v,val[tot]=w
#define LL long long
int N,tot;
LL tmp=0,ans=0,g=0;
int head[20005]={},nxt[40005]={},to[40005]={},val[40005]={};
int f[20005][3]={};
void dfs(int x,int fa)
{
	f[x][0]=1;
	for(int i=head[x];i;i=nxt[i])
	{
		if(to[i]==fa)continue;
		dfs(to[i],x);
		for(int j=0;j<3;++j)ans+=(LL)(f[to[i]][j]*f[x][((-j-val[i])%3+3)%3]*2);
		for(int j=0;j<3;++j)f[x][(val[i]+j)%3]+=f[to[i]][j];
	}
}
LL gcd(LL a,LL b){return !b?a:gcd(b,a%b);}
int main()
{
	scanf("%d",&N);
	for(int a,b,c,i=1;i<N;++i)
	{
		scanf("%d%d%d",&a,&b,&c);
		add_edge(a,b,c); add_edge(b,a,c);
	}
	dfs(1,0);
	ans+=N;
	tmp=N*N;
	g=gcd(ans,tmp);
	ans/=g; tmp/=g;
	printf("%lld/%lld",ans,tmp);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Estia_/article/details/82902905