BZOJ 2152: 聪聪可可 树分治

2152: 聪聪可可


Description

聪聪和可可是兄弟俩,他们俩经常为了一些琐事打起来,例如家中只剩下最后一根冰棍而两人都想吃、两个人都想玩儿电脑(可是他们家只有一台电脑)……遇到这种问题,一般情况下石头剪刀布就好了,可是他们已经玩儿腻了这种低智商的游戏。他们的爸爸快被他们的争吵烦死了,所以他发明了一个新游戏:由爸爸在纸上画n个“点”,并用n-1条“边”把这n个“点”恰好连通(其实这就是一棵树)。并且每条“边”上都有一个数。接下来由聪聪和可可分别随即选一个点(当然他们选点时是看不到这棵树的),如果两个点之间所有边上数的和加起来恰好是3的倍数,则判聪聪赢,否则可可赢。聪聪非常爱思考问题,在每次游戏后都会仔细研究这棵树,希望知道对于这张图自己的获胜概率是多少。现请你帮忙求出这个值以验证聪聪的答案是否正确。

Input

输入的第1行包含1个正整数n。后面n-1行,每行3个整数x、y、w,表示x号点和y号点之间有一条边,上面的数是w。

Output

以即约分数形式输出这个概率(即“a/b”的形式,其中a和b必须互质。如果概率为1,输出“1/1”)。

Sample Input

5
1 2 1
1 3 2
1 4 1
2 5 3

Sample Output

13/25
【样例说明】
13组点对分别是(1,1) (2,2) (2,3) (2,5) (3,2) (3,3) (3,4) (3,5) (4,3) (4,4) (5,2) (5,3) (5,5)。

【数据规模】
对于100%的数据,n<=20000。

HINT

 

题解

  树分治

  对于一棵树get它的deep时保存%3下为0,1,2上计数就好了

  在以u为根的子树上 答案就是 deep[0] * deep[0] + 2 * deep[1] * deep[2];

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N = 5e4+20, M = 4e4+10, mod = 1e9+7, inf = 0x3f3f3f3f;

int n, deep[N], d[N], head[N], t=1, f[N], siz[N], vis[N], root, allnode, ans;
int gcd(int a,int b) {return b==0?a:gcd(b,a%b);}
struct edg{int to,next,w;}e[N * 4];
void add(int u,int v,int w) {e[t].next=head[u]; e[t].to=v; e[t].w=w;head[u]=t++;}
void getroot(int u,int fa) {
    siz[u] = 1;
    f[u] = 0;
    for(int i = head[u]; i; i = e[i].next) {
        int to = e[i].to;
        if(to == fa || vis[to]) continue;
        getroot(to,u);
        siz[u] += siz[to];
        f[u] = max(f[u],siz[to]);
    }
    f[u] = max(f[u],allnode - siz[u]);
    if(f[u] < f[root]) root = u;
}
void getdeep(int u,int fa) {
    deep[d[u] % 3]++;
    //cout<<u<<endl;
    for(int i = head[u]; i; i = e[i].next) {
        int to = e[i].to;
        if(to == fa || vis[to]) continue;
        d[to] = d[u] + e[i].w;
        getdeep(to,u);
    }
}
int cal(int u,int now)
{
    d[u]=now;deep[0]=deep[1]=deep[2]=0;
    getdeep(u,0);
    return deep[0] * deep[0] + 2 * deep[1] * deep[2];
}
void work(int u) {
    vis[u] = 1;
    ans += cal(u,0);
   // for(int i = 0; i <= 2; ++i) cout<<deep[i]<<endl;
    //return ;
    for(int i = head[u]; i; i = e[i].next) {
        int to = e[i].to;
        if(vis[to]) continue;
        ans -= cal(to,e[i].w);
       allnode = siz[to];
        root = 0;
        getroot(to,-1);
        work(root);

    }
   // cout<<ans<<endl;
}
int main()
{
    scanf("%d",&n);
    for(int i = 1; i < n; ++i) {
        int a,b,c;
        scanf("%d%d%d",&a,&b,&c);
        add(a,b,c);
        add(b,a,c);
    }
    root=ans=0;
    f[0]=inf;allnode = n;
    getroot(1,-1);
    work(root);
    int tot = n*n;
    printf("%d/%d\n",ans/gcd(ans,tot),tot/gcd(ans,tot));
}

 

posted @ 2016-07-29 14:20  meekyan  阅读(170)  评论(0编辑  收藏  举报