http://acm.hdu.edu.cn/showproblem.php?pid=4035
经典概率DP。
#include <ctime>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
const int maxn = 10010;
double k[maxn], e[maxn];
double A[maxn], B[maxn], C[maxn];
vector<int> g[maxn];
/**
dp求期望的题。
题意:
有n个房间,由n-1条隧道连通起来,实际上就形成了一棵树,
从结点1出发,开始走,在每个结点i都有3种可能:
1.被杀死,回到结点1处(概率为ki)
2.找到出口,走出迷宫 (概率为ei)
3.和该点相连有m条边,随机走一条
求:走出迷宫所要走的边数的期望值。
设 E[i]表示在结点i处,要走出迷宫所要走的边数的期望。E[1]即为所求。
叶子结点:
E[i] = ki*E[1] + ei*0 + (1-ki-ei)*(E[father[i]] + 1);
= ki*E[1] + (1-ki-ei)*E[father[i]] + (1-ki-ei);
非叶子结点:(m为与结点相连的边数)
E[i] = ki*E[1] + ei*0 + (1-ki-ei)/m*( E[father[i]]+1 + ∑( E[child[i]]+1 ) );
= ki*E[1] + (1-ki-ei)/m*E[father[i]] + (1-ki-ei)/m*∑(E[child[i]]) + (1-ki-ei);
设对每个结点:E[i] = Ai*E[1] + Bi*E[father[i]] + Ci;
对于非叶子结点i,设j为i的孩子结点,则
∑(E[child[i]]) = ∑E[j]
= ∑(Aj*E[1] + Bj*E[father[j]] + Cj)
= ∑(Aj*E[1] + Bj*E[i] + Cj)
带入上面的式子得
(1 - (1-ki-ei)/m*∑Bj)*E[i] = (ki+(1-ki-ei)/m*∑Aj)*E[1] + (1-ki-ei)/m*E[father[i]] + (1-ki-ei) + (1-ki-ei)/m*∑Cj;
由此可得
Ai = (ki+(1-ki-ei)/m*∑Aj) / (1 - (1-ki-ei)/m*∑Bj);
Bi = (1-ki-ei)/m / (1 - (1-ki-ei)/m*∑Bj);
Ci = ( (1-ki-ei)+(1-ki-ei)/m*∑Cj ) / (1 - (1-ki-ei)/m*∑Bj);
对于叶子结点
Ai = ki;
Bi = 1 - ki - ei;
Ci = 1 - ki - ei;
从叶子结点开始,直到算出 A1,B1,C1;
E[1] = A1*E[1] + B1*0 + C1;
所以
E[1] = C1 / (1 - A1);
若 A1趋近于1则无解...
**/
bool dfs(int u, int p) {
// 叶子节点
if(g[u].size() == 1 && p != -1) {
A[u] = k[u];
B[u] = 1 - k[u] - e[u];
C[u] = 1 - k[u] - e[u];
return true;
}
int size = g[u].size();
A[u] = k[u];
B[u] = (1 - k[u] - e[u]) / size;
C[u] = 1 - k[u] - e[u];
double t1 = 0, t2 = 0, t3 = 0;
for(int i = 0; i < size; ++i) {
int v = g[u][i];
if(v == p) continue;
if(!dfs(v, u)) continue;
t1 += A[v];
t2 += B[v];
t3 += C[v];
}
double t = 1 - (1 - k[u] - e[u]) / size * t2;
if(abs(t) < 1e-10) return false;
A[u] += (1 - k[u] - e[u]) / size * t1;
A[u] /= t;
B[u] /= t;
C[u] += (1 - k[u] - e[u]) / size * t3;
C[u] /= t;
return true;
}
int main() {
//freopen("aa.in", "r", stdin);
int T, n, x, y;
int kcase = 0;
scanf("%d", &T);
while(T--) {
kcase++;
for(int i = 0; i < maxn; ++i) g[i].clear();
scanf("%d", &n);
for(int i = 1; i < n; ++i) {
scanf("%d %d", &x, &y);
g[x].push_back(y);
g[y].push_back(x);
}
for(int i = 1; i <= n; ++i) {
scanf("%lf %lf", &k[i], &e[i]);
k[i] /= 100.0;
e[i] /= 100.0;
}
printf("Case %d: ", kcase);
if(!dfs(1, -1) || abs(A[1]-1.0) < 1e-10) {
printf("impossible\n");
} else {
printf("%.6lf\n", C[1]/(1.0-A[1]));
}
}
return 0;
}