题目链接:https://jzoj.net/senior/#main/show/6101
记(f_i)为从(i)号点走到(n)号点所花天数的期望
那么根据(m)条边等可能的出现一条和一定会往期望值较小的点走的贪心策略我们可以得到
[f_i=frac{1}{m}sum min(f_i,f_j)+1
]
其中当(i,j)不相连的时候可将(f_j)看做无限大
我们考虑在该式子中一共选取了(sum)次(f_j),也就是(m-sum)次(f_i),那么
[f_i=frac{1}{m}(sum _{f_j<f_i}f_j+(m-sum)*f_i)+1
]
两边同时乘(m)并移项
[sum*f_i=sum f_j+m
]
即
[f_i=frac{sum f_j+m}{sum}
]
我们将(f_i)看做到(n)点的距离,直接跑最短路,当从队列首部拎出来的(u)存在一条边((u,v))使得当前的(f_v)比(f_u)大时就更新答案
那么我们如何维护这个优先队列呢?
我们假设当前用(f_k)去更新(f_i),那么就会有
[frac{sum f_j+m+f_k}{sum+1}<frac{sum f_j+m}{sum}
]
去分母化简得到
[f_k<frac{sum f_j+m}{sum}
]
所以直接按照(frac{sum f_j+m}{sum})的值从小到大维护该队列即可
#include<iostream>
#include<string.h>
#include<string>
#include<stdio.h>
#include<algorithm>
#include<math.h>
#include<vector>
#include<queue>
#include<map>
#include<set>
using namespace std;
#define lowbit(x) (x)&(-x)
#define rep(i,a,b) for (int i=a;i<=b;i++)
#define per(i,a,b) for (int i=a;i>=b;i--)
#define maxd 1000000007
typedef long long ll;
const int N=100000;
const double pi=acos(-1.0);
struct node{
int to,nxt;
}sq[200200];
struct hnode{
int u,sum;double f;
};
bool operator<(const hnode &p,const hnode &q)
{
return p.f*q.sum>q.f*p.sum;
}
priority_queue<hnode> q;
int n,m,all=0,head[100100],sum[100100];
double f[100100];
bool vis[100100];
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*10+(ch-'0');ch=getchar();}
return x*f;
}
void add(int u,int v)
{
all++;sq[all].to=v;sq[all].nxt=head[u];head[u]=all;
}
double dij()
{
memset(vis,0,sizeof(vis));
sum[n]=1;q.push((hnode){n,1,0});
while (!q.empty())
{
int u=q.top().u;q.pop();
if (vis[u]) continue;
vis[u]=1;int i;
double now=(f[u]+m)/sum[u];
if (u==1) return (f[u]+m)/sum[u];
else if (u==n) now=0;
for (i=head[u];i;i=sq[i].nxt)
{
int v=sq[i].to;
if ((sum[v]==0) || ((f[v]+m)>now*sum[v]))
{
f[v]+=now;sum[v]++;
if (!vis[v]) q.push((hnode){v,sum[v],f[v]+m});
}
}
}
}
int main()
{
freopen("path.in","r",stdin);
freopen("path.out","w",stdout);
n=read();m=read();
rep(i,1,m)
{
int u=read(),v=read();
add(u,v);add(v,u);
}
double ans=dij();
printf("%0.8lf",ans);
return 0;
}