zoukankan      html  css  js  c++  java
  • 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
    ", x,y);
    }
    
  • 相关阅读:
    struts2知识系统整理
    JavaScript onload
    百度云如何为用户分配内存空间
    集合运算
    [hdu3530]单调队列
    [hdu4911]逆序对相关
    [hdu5199]统计数据的水题
    [hdu5200]离线+标记
    [hdu5204]水题
    [hdu5203]计数水题
  • 原文地址:https://www.cnblogs.com/uid001/p/10981833.html
Copyright © 2011-2022 走看看