BZOJ 3566: [SHOI2014]概率充电器

题目:http://www.lydsy.com/JudgeOnline/problem.php?id=3566

首先这题正着想不好想,考虑补集转化。

先dfs一遍,令f[u]=(1-p[u])*∏(1-(1-f[v])*w) f[u]表示u这个点通过其子树并不能联通的概率。

然后考虑v从其父亲连过来的情况,设x=1-f[u]/(1-(1-f[v])*w)表示除掉v,u联通的概率,那么f[v]*=(1-x*w)

然后加起来就是答案了。

#include<cstring>
#include<iostream>
#include<algorithm>
#include<cstdio>
#define maxn 500500
#define rep(i,l,r) for (int i=l;i<=r;i++)
#define down(i,l,r) for (int i=l;i>=r;i--)
#define clr(x,y) memset(x,y,sizeof(x))
#define eps 1e-8
using namespace std;
struct data{int obj,pre; double c;
}e[maxn*2];
int head[maxn],tot,n;
double f[maxn],ans,p[maxn];
int read(){
    int x=0,f=1; char ch=getchar();
    while (!isdigit(ch)){if (ch=='-') f=-1; ch=getchar();}
    while (isdigit(ch)) {x=x*10+ch-'0'; ch=getchar();}
    return x*f;
}
void insert(int x,int y,double z){
    e[++tot].obj=y; e[tot].c=z; e[tot].pre=head[x]; head[x]=tot;
}
void dfs(int u,int fa){
    f[u]=1-p[u];
    for (int j=head[u];j;j=e[j].pre){
        int v=e[j].obj;
        if (v!=fa) {
            dfs(v,u); 
            f[u]=f[u]*(1-(1-f[v])*e[j].c);
        }
     }
}
void go(int u,int fa){
    for (int j=head[u];j;j=e[j].pre){
        int v=e[j].obj;
        if (v!=fa){
            double x=1-f[u]/(1-(1-f[v])*e[j].c);
            if (x>eps&&f[v]>eps)f[v]=f[v]*(1-x*e[j].c);
            go(v,u);
        }
    }
}
int main(){
    n=read();
    rep(i,1,n-1){
        int x=read(),y=read(),z=read();
        insert(x,y,1.0*z/100); insert(y,x,1.0*z/100);
    }
    rep(i,1,n) {int x=read(); p[i]=1.0*x/100;}
    dfs(1,0);
    go(1,0);
    rep(i,1,n) ans+=1-f[i];
    printf("%.6lf
",ans);
    return 0;
}
原文地址:https://www.cnblogs.com/ctlchild/p/5105390.html