绿豆蛙&概率期望dp
绿豆蛙的归宿
题目大意
给定一个
每个点连出去
第一种方法—逆推
思路
拆解题目,先考虑从点
设集合
则可以写出式子:
其中
乘上
而
代码
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 1e5 + 10, M = 998244353;
int n, m, in[N];
double dp[N];
struct Node{
int x, w;
};
vector<Node> v[N];
vector<int> ans;
queue<int> q;
void topo(){
for(int i = 1; i <= n; i++){
if(!in[i]){
q.push(i);
}
}
while(q.size()){
int p = q.front();
q.pop();
ans.push_back(p);
for(auto i : v[p]){
in[i.x]--;
if(in[i.x] == 0){
q.push(i.x);
}
}
}
}
int main(){
ios::sync_with_stdio(0), cin.tie(0);
cin >> n >> m;
for(int i = 1, x, y, w; i <= m; i++){
cin >> x >> y >> w;
v[x].push_back({y, w});
in[y]++;
}
topo();
reverse(ans.begin(), ans.end());
for(int i : ans){
for(auto j : v[i]){
dp[i] += (dp[j.x] + j.w) / (int)v[i].size();
}
}
cout << fixed << setprecision(2) << dp[1];
return 0;
}
第二种方法—正推
思路
如果是正推的话,那么问题可以拆分成:
求出从起点到点
还是与之前差不多的转移图。
变量定义与前面差不多,只是集合
则可以推出转移式:
1.
2.
这里的
因为现在是从起点走到点
再次化简:
化简完成,再对比一下之前的式子
是不是多了一个
因为正着推的话,从起点走到点
代码
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define int ll
const int N = 1e5 + 10;
int n, m, ans, in[N];
double E[N], P[N];
struct Node{
int x, w;
};
vector<Node> v[N];
vector<int> order;
queue<int> q;
void topo(){
P[1] = 1;
for(int i = 1; i <= n; i++){
if(!in[i]){
q.push(i);
}
}
while(q.size()){
int p = q.front();
q.pop();
double tmp = v[p].size();
for(auto i : v[p]){
E[i.x] += 1 / tmp * (E[p] + P[p] * i.w);
P[i.x] += P[p] / tmp;
if(!--in[i.x]){
q.push(i.x);
}
}
}
}
signed main(){
ios::sync_with_stdio(0);
cin >> n >> m;
for(int i = 1, x, y, w; i <= m; i++){
cin >> x >> y >> w;
v[x].push_back({y, w});
in[y]++;
}
topo();
cout << fixed << setprecision(2) << E[n];
return 0;
}
第二种方法—期望线性性
思路
可以考虑每条边对答案的贡献。
先设
可推出式子:
为什么是
因为这条边可走可不走。
那
而
所以最后的式子为:
于是求解经过一条边的概率即可。
代码
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define int ll
const int N = 1e5 + 10;
int n, m, in[N];
double P[N], ans;
struct Node{
int x, w;
};
vector<Node> v[N];
queue<int> q;
void topo(){
P[1] = 1;
for(int i = 1; i <= n; i++){
if(!in[i]){
q.push(i);
}
}
while(q.size()){
int p = q.front();
q.pop();
double tmp = v[p].size();
for(auto i : v[p]){
P[i.x] += P[p] / tmp;
ans += 1.00 * i.w * (P[p] / tmp);
if(!--in[i.x]){
q.push(i.x);
}
}
}
}
signed main(){
ios::sync_with_stdio(0);
cin >> n >> m;
for(int i = 1, x, y, w; i <= m; i++){
cin >> x >> y >> w;
v[x].push_back({y, w});
in[y]++;
}
topo();
cout << fixed << setprecision(2) << ans;
return 0;
}