bzoj2152 聪聪可可 (树形dp)
Posted uid001
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了bzoj2152 聪聪可可 (树形dp)相关的知识,希望对你有一定的参考价值。
大意: 给定树, 随机选两点, 求两点距离是3的倍数的概率.
树形dp入门水题, 枚举每个点作为lca时的答案即可.
#include <iostream> #include <queue> #define REP(i,a,n) for(int i=a;i<=n;++i) using namespace std; typedef long long ll; ll gcd(ll a,ll b) return b?gcd(b,a%b):a; const int N = 1e6+10; int n, dp[N][3]; struct _ int to,w;; vector<_> g[N]; ll ans; void dfs(int x, int fa, int d) for (int i=0; i<g[x].size(); ++i) int y = g[x][i].to; if (y==fa) continue; dfs(y,x,(d+g[x][i].w)%3); ans += 2ll*dp[y][d]; REP(i,0,2) ans += 2ll*dp[x][i]*dp[y][(2*d-i+3)%3]; REP(i,0,2) dp[x][i] += dp[y][i]; ++dp[x][d],++ans; int main() scanf("%d", &n); REP(i,2,n) int u, v, w; scanf("%d%d%d", &u, &v, &w); w %= 3; g[u].push_back(v,w); g[v].push_back(u,w); dfs(1,0,0); ll x = ans, y = (ll)n*n, z = gcd(x,y); x /= z, y /= z; printf("%lld/%lld\n", x,y);
以上是关于bzoj2152 聪聪可可 (树形dp)的主要内容,如果未能解决你的问题,请参考以下文章