聪聪可可

题目描述

聪聪和可可是兄弟俩,他们俩经常为了一些琐事打起来,例如家中只剩下最后一根冰棍而两人都想吃、两个人都想玩儿电脑(可是他们家只有一台电脑)……遇到这种问题,一般情况下石头剪刀布就好了,可是他们已经玩儿腻了这种低智商的游戏。

他们的爸爸快被他们的争吵烦死了,所以他发明了一个新游戏:由爸爸在纸上画n个“点”,并用n-1条“边”把这n个“点”恰好连通(其实这就是一棵树)。并且每条“边”上都有一个数。接下来由聪聪和可可分别随即选一个点(当然他们选点时是看不到这棵树的),如果两个点之间所有边上数的和加起来恰好是3的倍数,则判聪聪赢,否则可可赢。

聪聪非常爱思考问题,在每次游戏后都会仔细研究这棵树,希望知道对于这张图自己的获胜概率是多少。现请你帮忙求出这个值以验证聪聪的答案是否正确。

输入输出格式

输入格式:

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

输出格式:

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

输入输出样例

输入样例#1: 复制
5
1 2 1
1 3 2
1 4 1
2 5 3
输出样例#1: 复制
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。

思路:树上点分治,余数有1和2的组合以及0和0的组合,乘法原理,注意判断一下点是否已经访问过了,避免陷入死循环。

#include<bits/stdc++.h>
#define REP(i, a, b) for(int i = (a); i <= (b); ++ i)
#define REP(j, a, b) for(int j = (a); j <= (b); ++ j)
#define PER(i, a, b) for(int i = (a); i >= (b); -- i)
using namespace std;
const int maxn=2e5+5;
template <class T>
inline void rd(T &ret){
    char c;
    ret = 0;
    while ((c = getchar()) < '0' || c > '9');
    while (c >= '0' && c <= '9'){
        ret = ret * 10 + (c - '0'), c = getchar();
    }
}
int head[maxn],n,cnt,tot,mz[maxn],siz[maxn],root,r[5],depth[maxn],cur,vis[maxn];
struct node{
     int to,w,nx;
}p[maxn];
void addedge(int u,int v,int w){
     p[++cnt]=(node){v,w,head[u]},head[u]=cnt;
}
void getroot(int u,int fa){
      siz[u]=1,mz[u]=0;
      for(int i=head[u];i;i=p[i].nx){
           int to=p[i].to;
           if(to!=fa&&!vis[to]){
               getroot(to,u);
               siz[u]+=siz[to],mz[u]=max(mz[u],siz[to]);
           }
      }
      mz[u]=max(mz[u],tot-mz[u]);
      if(mz[u]<mz[root])root=u;
}
void getdeep(int u,int fa){
    r[depth[u]]++;
    for(int i=head[u];i;i=p[i].nx){
        int to=p[i].to;
        if(to==fa||vis[to])continue;
        depth[to]=(depth[u]+p[i].w)%3;
        getdeep(to,u);
    }
}
int gt(int u,int val){
     r[0]=r[1]=r[2]=0;
     depth[u]=val;
     getdeep(u,0);
     return r[1]*r[2]*2+r[0]*r[0];
}
void solve(int rt){
     cur+=gt(rt,0);
     vis[rt]=1;
     for(int i=head[rt];i;i=p[i].nx){
        int to=p[i].to;
        if(vis[to])continue;
        cur-=gt(to,p[i].w);
        root=0,tot=siz[to];
        getroot(to,0);
        solve(root);
     }
}
int gcd(int a,int b){return (!b)?a:gcd(b,a%b);}
int main()
{
    rd(n);
    REP(i,1,n-1){
         int x,y,z;
         rd(x),rd(y),rd(z);
         addedge(x,y,z%3),addedge(y,x,z%3);
    }
    tot=mz[0]=n,root=0;
    getroot(1,0);
    solve(root);
    int q=gcd(cur,n*n);
    cout<<cur/q<<'/'<<n*n/q<<endl;
    return 0;
}
原文地址:https://www.cnblogs.com/czy-power/p/10401832.html