题解:P15446 「IXOI R1」BA BA 博弈

· · 题解

论题目名应该怎么读。

题意

给定一棵以 1 为根的有根树,小 B 不知道树的结构,他从根节点开始,每次随机走到一个儿子直到走到叶子。小 A 知道树的结构并每次可以走到任意一个叶子。小 A 还可以可以通过一次操作得知小 B 的位置。当结束时两人在同一位置则小 A 胜,否则小 B 胜。求最大化小 A 胜率的情况下最少操作次数的期望。

Solution

首先到达每个点的概率是好算的。

考虑维护当前可能到达的节点集合 S。

当 S 中没有一个点一个的儿子为叶子时,我们不需要操作,到后面再操作显然可以得知更精确的信息。

当 S 中存在且仅存在一个点的儿子为叶子时,我们不需要知道小 B 是否在那个点,只要移动过去即可,因此也不需要进行操作。

当 S 中存在两个及以上的点的儿子为叶子时,为了最大化胜率我们就必须先知道小 B 在哪个节点,因此需要进行一次操作。此时我们得知他在哪个节点后再以其为根求解子问题即可。

对于到达每个 S 的概率显然就是 S 中所有点的概率之和。

视实现复杂度为 \mathcal O(N) 或 \mathcal O(N\log N)。

::::success[Code]

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned ll
const int N=1e6+5;
const ll mod=1e9+7;
int n,f[N];
ll inv[N],ans,p[N];
bool ck[N],lf[N];
vector<int>e[N];
ll Pow(ll x,ll y){
    ll res(1);
    while(y){
        if(y&1)(res*=x)%=mod;
        (x*=x)%=mod;
        y>>=1;
    }
    return res;
}
void init(int u,int fa){
    if(u!=1&&e[u].size()==1)ck[fa]=lf[u]=1;
    f[u]=fa;
    for(auto v : e[u])
        if(v!=fa)init(v,u);
}
void find(int u){
    set<int>S;
    S.insert(u);
    while(!S.empty()){
        set<int>T;
        int tot(0);
        ll o(0);
        for(auto x : S){
            int dg=(x==1)+e[x].size()-1;
            for(auto v : e[x])
                if(v!=f[x]){
                    p[v]=p[x]*inv[dg]%mod;
                    if(lf[v])continue;
                    else if(ck[v])++tot;
                    (o+=p[v])%=mod;
                    T.insert(v);
                }
        }
        S=T;
        if(tot>1){
            (ans+=o)%=mod;
            for(auto v : S)
                find(v);
            return;
        }
    }
}
int main(){
    scanf("%d",&n);
    for(int i=1,u,v;i<n;++i){
        scanf("%d%d",&u,&v);
        e[u].push_back(v);
        e[v].push_back(u);
    }
    for(int i=1;i<=n;++i)
        inv[i]=Pow(i,mod-2);
    init(1,0);
    p[1]=1;
    find(1);
    printf("%lld",ans);
    return 0;
}

::::