BZOJ:2152(点分治)

题目大意:

给一棵树,树上每个边有权值,AB每次从树中随机选择两个点,如果两点间点的权值和为3的倍数,则A获胜,否则B获胜。A比赛完后会对树进行研究,想知道他能获胜的概率是多少。

解题思路:

其实就是点分治,对于重心V,我们统计出它两边权值和分别%3为0为1为2的个数,

那么对于重心V的答案就是 d[1]*d[2]*2+d[0]*d[0],这些就是A能够获胜的方案,然后再减去重复计算的即可。

Ac代码:

#include<bits/stdc++.h>
#define size si
using namespace std;
typedef long long ll;
const int maxn=1e5+5;
const int INF=1e9+7;
ll gcd(ll a,ll b) { return b?gcd(b,a%b):a;}
int n,k;
ll res;
struct Edge
{
    int to,next,w;
}e[maxn];
int head[maxn],tot;
bool vis[maxn];
void add(int u,int v,int w)
{
    e[tot].to=v;e[tot].w=w;
    e[tot].next=head[u];head[u]=tot++;
}
int tmp,root,num,size[maxn],mx[maxn],dep[maxn];
void init() //初始化
{
    tot=0; res=0;
    memset(head,-1,sizeof head);
    memset(vis,0,sizeof vis);
}
void getsize(int x,int fa)  //得到size 以及 mx
{
    size[x]=1;mx[x]=0;
    for(int i=head[x];i!=-1;i=e[i].next)
    {
        int to=e[i].to;
        if(to==fa||vis[to]) continue;
        getsize(to,x);
        size[x]+=size[to];
        mx[x]=max(mx[x],size[to]);
    }
}
void getroot(int r,int x,int fa)    //找出重心
{
    mx[x]=max(mx[x],size[r]-size[x]);
    if(mx[x]<tmp) tmp=mx[x],root=x;
    for(int i=head[x];i!=-1;i=e[i].next)
    {
        int to=e[i].to;
        if(to==fa||vis[to]) continue;
        getroot(r,to,x);
    }
}
void getdep(int x,int deep,int fa)  //得到dep数组
{
    dep[deep%3]++;
    for(int i=head[x];i!=-1;i=e[i].next)
    {
        int to=e[i].to;
        if(to==fa||vis[to]) continue;
        getdep(to,deep+e[i].w,x);
    }
}
ll cal(int v,int d)    //统计当前子树的答案
{
	dep[0]=dep[1]=dep[2]=0;
    getdep(v,d,0);
    return 1LL*dep[0]*dep[0]+dep[1]*dep[2]*2;	//返回答案
}
void dfs(int v) //遍历所有子树
{
    tmp=n;
    getsize(v,0);
    getroot(v,v,0);
    res+=cal(root,0);
    vis[root]=1;
    for(int i=head[root];i!=-1;i=e[i].next)
    {
        int to=e[i].to;
        if(!vis[to])
        {
            res-=cal(to,e[i].w);	//去重
            dfs(to);
        }
    }
}
int main()
{
    while(scanf("%d",&n)!=EOF)
    {
        init();
        for(int i=1;i<n;i++)
        {
            int x,y,z;
            scanf("%d%d%d",&x,&y,&z);
            add(x,y,z);
            add(y,x,z);
        }
        dfs(1);
		ll gk=1LL*n*n;
		ll gc=gcd(res,gk);
        printf("%lld/%lld\n",res/gc,gk/gc);
    }
}

猜你喜欢

转载自blog.csdn.net/f2935552941/article/details/81503198