P2634 [国家集训队]聪聪可可

题目描述

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

他们的爸爸快被他们的争吵烦死了,所以他发明了一个新游戏:由爸爸在纸上画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。

代码

树上直接统计

注意答案要乘以2((x,y),(y,x))加上n(0也算作3的倍数);

#include<bits/stdc++.h>
#define inf 0x3f3f3f3f
using namespace std;
const int maxn=20000+100;
int head[maxn];
int p[maxn],t[maxn];
int ms[maxn],s[maxn];
int dis[maxn],vis[maxn],d[maxn];
int sum,rt=0,ans=0;
struct edge
{
    int to,next,val;
}e[maxn<<1];
int size=0;
inline int read()
{
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=(x<<3)+(x<<1)+ch-'0';ch=getchar(); }
    return x*f;
}
void addedge(int u,int v,int w)
{
    e[++size].to=v;e[size].val=w;e[size].next=head[u];head[u]=size;
}
void fc(int u,int fa)
{
    s[u]=1,ms[u]=0;
    for(int i=head[u];i;i=e[i].next)
    {
        int to=e[i].to;
        if(to==fa||vis[to])continue;
        fc(to,u);
        s[u]+=s[to];
        ms[u]=max(ms[u],s[to]);
    }
    ms[u]=max(ms[u],sum-ms[u]);
    if(ms[rt]>ms[u])rt=u;
}
void dfs(int u,int fa)
{
    d[++d[0]]=dis[u]%3;
    for(int i=head[u];i;i=e[i].next)
    {
        int to=e[i].to;
        if(to==fa||vis[to])continue;
        dis[to]=dis[u]+e[i].val;        
        dfs(to,u);
    }
}
void cal(int u)
{
    int tot=0;
    for(int i=head[u];i;i=e[i].next)
    {
        int to=e[i].to;
        if(vis[to])continue;
        d[0]=0,dis[to]=e[i].val;
        dfs(to,u);
        for(int j=1;j<=d[0];j++)
        ans+=p[(3-d[j])%3];
        for(int j=1;j<=d[0];j++)
        t[++tot]=d[j],p[d[j]]++;
    }
    for(int i=1;i<=tot;i++)
    p[t[i]]=0; 
}
void solve(int u)
{
    vis[u]=p[0]=1;cal(u);
    for(int i=head[u];i;i=e[i].next)
    {
        int to=e[i].to;
        if(vis[to])continue;
        sum=s[to],ms[rt]=inf;
        fc(to,u);solve(rt);
    }
}
int gcd(int x,int y)
{
    return y==0?x:gcd(y,x%y);
}
int main()
{
    int n=read();
    for(int i=1;i<n;i++)
    {
        int u=read(),v=read(),w=read();
        addedge(u,v,w);addedge(v,u,w);
    }
    sum=n,ms[rt]=inf;
    fc(1,0); 
    solve(rt);
    ans=ans*2+n; 
    int g=gcd(ans,n*n);
    int a=ans/g,b=n*n/g;
    printf("%d/%d",a,b); 
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/DriverBen/p/10999601.html