【HDU4035】Maze
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 #include <iostream> 5 #include <vector> 6 #include <cmath> 7 8 using namespace std; 9 const int maxn=10000+100; 10 int T,n; 11 double E[maxn],K[maxn],A[maxn],B[maxn],C[maxn]; 12 vector<int>G[maxn]; 13 bool dfs(int u,int fa){ 14 double temp=0; 15 if(G[u].size()==1&&fa!=-1){ 16 A[u]=K[u]; 17 B[u]=1-K[u]-E[u]; 18 C[u]=1-K[u]-E[u]; 19 return true; 20 } 21 A[u]=K[u]; 22 B[u]=(1-K[u]-E[u])/G[u].size(); 23 C[u]=1-K[u]-E[u]; 24 for(int i=0;i<G[u].size();i++){ 25 int v=G[u][i]; 26 if(v!=fa){ 27 if(!dfs(v,u))return false; 28 A[u]+=A[v]*(1-K[u]-E[u])/G[u].size(); 29 C[u]+=(1-K[u]-E[u])/G[u].size()*C[v]; 30 temp+=B[v]*(1-K[u]-E[u])/G[u].size(); 31 } 32 } 33 if(fabs(1-temp)<=1e-10)return false; 34 A[u]/=(1-temp); 35 B[u]/=(1-temp); 36 C[u]/=(1-temp); 37 return true; 38 } 39 int main(){ 40 scanf("%d",&T); 41 for(int t=1;t<=T;t++){ 42 memset(A,0,sizeof(A)); 43 memset(B,0,sizeof(B)); 44 memset(C,0,sizeof(C)); 45 scanf("%d",&n); 46 for(int i=1;i<=n;i++)G[i].clear(); 47 int x,y; 48 for(int i=1;i<n;i++){ 49 scanf("%d%d",&x,&y); 50 G[x].push_back(y); 51 G[y].push_back(x); 52 } 53 for(int i=1;i<=n;i++){ 54 scanf("%lf%lf",&K[i],&E[i]); 55 K[i]/=100,E[i]/=100; 56 } 57 printf("Case %d: ",t); 58 if(!dfs(1,-1)||(1-A[1])<=1e-10){ 59 printf("impossible\n"); 60 continue; 61 } 62 /* for(int i=1;i<=n;i++){ 63 cout<<i<<" "<<C[i]<<endl; 64 }*/ 65 printf("%.6f\n",C[1]/(1-A[1])); 66 } 67 return 0; 68 }