2019 南京网络赛 D.Robots(DAG求期望dp)

题目大意:在一个DAG上,保证所有的点都在 1 -> n的路径上,机器人在 i 点时可以等概率的选择沿有向边走到相邻点或呆在原点,每过一天机器人花费的能量是已经过去的天数之和,问 从 1号点走到号点的花费能量的期望。


(题都读错了,读成了一般有向图)
做法:显然可以从 n 号点倒推推出 从i 号点走到号点的期望天数,设为dp[i]。转移方程: d p [ i ] = ( ∑ &lt; i , j &gt; ∈ E d p [ j ] d [ i ] + 1 ) + d p [ i ] d [ i ] + 1 + 1 dp[i] = (\sum_{&lt;i,j&gt; \in E}\frac{dp[j]}{d[i] +1}) + \frac{dp[i]}{d[i] + 1} + 1 dp[i]=(<i,j>Ed[i]+1dp[j])+d[i]+1dp[i]+1
设 cost[i] :从 i 点走到 n号点的期望花费。转移方程: c o s t [ i ] = ( ∑ &lt; i , j &gt; ∈ E c o s t [ j ] + d p [ i ] d [ i ] + 1 ) + c o s t [ i ] d [ i ] + 1 + d p [ i ] d [ i ] + 1 cost[i] = (\sum_{&lt;i,j&gt; \in E}\frac{cost[j] +dp[i]}{d[i] +1}) +\frac{cost[i]}{d[i] + 1} + \frac{dp[i]}{d[i] +1} cost[i]=(<i,j>Ed[i]+1cost[j]+dp[i])+d[i]+1cost[i]+d[i]+1dp[i]

cost[i]的转移方程什么意思:假设已经计算出cost[j],显然从 i 号点走到 j会增加从j走到 n 的花费,具体增加多少:从 i -> j 要花费一天,之后j的起步花费都会多1,从 i 到 n 要几天总花费就会增加多少。


#include<bits/stdc++.h>
using namespace std;
const int maxn = 3e6 + 10;
vector<int> g[maxn],h[maxn];
int t,n,m;
int d[maxn],d2[maxn];
double dp[maxn],cost[maxn];
void tpsort() {
	queue<int> q;
	q.push(n);
	while(!q.empty()) {
		int top = q.front();
		q.pop();
		dp[top] = 0;
		int p = (int)g[top].size() + 1;
		if(p > 1) {
			for(auto it : g[top])
				dp[top] += 1.0 * dp[it] / p;
			dp[top] += 1;
			dp[top] *= 1.0 * p / (p - 1);
		}
		for(auto it : h[top]) {
			d[it]--;
			if(!d[it]) q.push(it);
		}
	}
}
void tpsort2() {
	queue<int> q;
	q.push(n);
	while(!q.empty()) {
		int top = q.front();
		q.pop();
		cost[top] = 0;
		int p = (int)g[top].size() + 1;
		if(p > 1) {
			for(auto it : g[top])
				cost[top] += 1.0 * (cost[it] + dp[top]) / p;
			cost[top] += dp[top] / p;
			cost[top] *= 1.0 * p / (p - 1);
		}
		for(auto it : h[top]) {
			d2[it]--;
			if(!d2[it]) q.push(it);
		}
	}
	printf("%.2lf\n",cost[1]);
}
int main() {
	scanf("%d",&t);
	while(t--) {
		scanf("%d%d",&n,&m);
		fill(d,d + n + 1,0);
		fill(d2,d2 + n + 1,0);
		for(int i = 1; i <= m; i++) {
			int u,v;scanf("%d%d",&u,&v);
			g[u].push_back(v);
			h[v].push_back(u);
			d[u]++;d2[u]++;
		}
		cost[n] = dp[n] = 0;
		tpsort();
		tpsort2();
		for(int i = 1; i <= n; i++)
			h[i].clear(),g[i].clear();		
	}
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值