The Preliminary Contest for ICPC Asia Nanjing 2019 D Robots

本文探讨了一个关于机器人在无环有向图中从特定起点到终点的路径上,每日随机移动或静止并消耗等同于已过天数的问题。通过深入解析,采用期望DP算法,实现了对机器人到达终点所需平均天数的精确计算。

Robots

Given a directed graph with no loops which starts at node 11 and ends at node nn.
There is a robot who starts at 11, and will go to one of adjacent nodes or stand still with equal probability every day.
Every day the robot will have durability consumption which equals to the number of passed days.
Please calculate the expected durability consumption when the robot arrives at node nn.
It is guaranteed that there is only one node (node 1) whose in-degree is equal to 0,
and there is only one node (node n) whose out-degree is equal to 0. And there are no multiple edges in the graph.

Input
The first line contains one integer T (1≤T≤10)
For each case,the first line contains two integers n (2≤n≤10^5) and m (1≤m≤2×10^5), the number of nodes and the number of edges, respectively.
Each of the next mm lines contains two integers u and v (1≤u,v≤n) denoting a directed edge from u to v.
It is guarenteed that ∑n≤4×10^5, and ∑m≤5×10^5.

Output
Output T lines.Each line have a number denoting the expected durability consumption when the robot arrives at node n.
Please keep two decimal places.

样例输入
1
5 6
1 2
2 5
1 5
1 3
3 4
4 5
样例输出
9.78

题意

有n个点,1为起点,n为终点,起点入度为0,终点出度为0,保证起点终点唯一,每天可以选择转移到下一个点或者原地不动,每天的消耗为过去天数的总和,问你从起点到终点的期望天数是多少。

思路

期望dp

在这里插入图片描述
详细的状态转移方程可参照这个题解:https://blog.csdn.net/weixin_43847416/article/details/100318471

代码

#include<cstdio>
#include<cstring>
#include<algorithm>
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define ll long long
using namespace std;
#define maxn 200005
double dp[maxn], dp2[maxn];
int n;
vector<int> G[maxn];

void init(){
	for(int i = 0; i <= n; i++){
		G[i].clear();
		dp[i] = 0;
		dp2[i] = 0;
	}
}

void dfs(int now){
    int i, j;
    int lim = G[now].size();
    double q = 1.0/(double)lim;
    for(i = 0; i < lim; i++){
        int v = G[now][i];
        if(!dp[v]&&(v!=n)) dfs(v);
        dp[now] += q*dp[v];
    }
    dp[now] += (1.0+q);
}

void dfs2(int now){
    int i, j;
    int lim = G[now].size();
    double q = 1.0/(double)lim;
    for(i = 0; i < lim; i++){
        int v = G[now][i];
        if(!dp2[v]&&(v!=n)) dfs2(v);
        dp2[now] += q*dp2[v];
    }
    dp2[now] += (1.0+q)*dp[now];
}

int main(){
    int i, j, m, k, T;
    int u, v;
    scanf("%d",&T);
    while(T--){
    	init();
        scanf("%d%d",&n,&m);
        for(i = 1; i <= m; i++){
            scanf("%d%d",&u,&v);
            G[u].push_back(v);
        }
        dfs(1);
        dfs2(1);
        printf("%.2f\n",dp2[1]);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值