提高+省选-专题[期望dp][图论]:P4316 绿豆蛙的归宿

· · 个人记录

题目

华丽的分割线

解析

这是本蒟蒻的第一道概率期望dp

状态及方向

直接设元法,设f[i]表示走到第i个点的期望长度

若从1向n推,则不知道与1关联的点的信息,无法转移

按照期望dp的老办法,把状态反过来,从n向1转移

初始化及方程式

首先f[n]=0,对于第i个点,每条出边的概率\frac{1}{k}为i出度的倒数

由于求$f[i]$之前必须保证$i$出边所指向的点都求过 因为图为$DAG$,也就是在反图上跑拓扑排序,即为转移顺序 注意开$double

代码

#include<cstdio>
#define ll long long
using namespace std;
const int N=101000;
void read(int &x)
{
    x=0;
    int f;
    f=1;
    char c;
    c=getchar();
    while((c<'0'||c>'9')&&c!='-')
    {
        c=getchar();    
    }
    if(c=='-')
    {
        f=-1;
        c=getchar();
    }
    while(c>='0'&&c<='9')
    {
        x=(x<<3)+(x<<1)+(c^48);
        c=getchar();
    }
    x=x*f;
}
struct node
{
    int to;
    int val;
    int next;
};
node e[N*2];
int head[N],etot;
void add(int x,int y,int v)
{
    etot++;
    e[etot].val=v;
    e[etot].to=y;
    e[etot].next=head[x];
    head[x]=etot;
}
node e2[N*2];
int head2[N],etot2;
void add2(int x,int y,int v)
{
    etot2++;
    e2[etot2].val=v;
    e2[etot2].to=y;
    e2[etot2].next=head2[x];
    head2[x]=etot2;
}
int du[N],unlock[N],topu[N],toputot;
void dfs(int x)
{
    int i;
    for(i=head[x];i!=0;i=e[i].next)
    {
        unlock[e[i].to]--;
        if(unlock[e[i].to]==0)
        {
            toputot++;
            topu[toputot]=e[i].to;
            dfs(e[i].to);
        }
    }
}
double f[N];
int main()
{
    etot=0;
    toputot=0;
    int n,m,i,x,y,v,j;
    read(n);
    read(m);
    for(i=1;i<=m;i++)
    {
        read(x);
        read(y);
        read(v);
        add(y,x,v);
        add2(x,y,v);
        du[x]++;
        unlock[x]++;
    }
    dfs(n);
    f[n]=0.0;
    for(i=1;i<=toputot;i++)
    {
        for(j=head2[topu[i]];j!=0;j=e2[j].next)
        {
            f[topu[i]]+=(f[e2[j].to]+(double)e2[j].val)/(double)du[topu[i]];
        }
    }
    printf("%.2lf",f[1]);
}