Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.94 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4.  
  5. double dfs(const int u, const int parent, const int snk, vector<bool> & visited,vector<double> & dp, const vector<vector<pair<int, double>>> & e) {
  6.    
  7.     if (u == snk) return 1;
  8.    
  9.     if (dp[u] != -1) return dp[u]; // visited a processed cousin/sibling
  10.  
  11.     if (visited[u]) return 0; // visited a grand-parent
  12.  
  13.     visited[u] = 1;
  14.  
  15.     int nodeCnt = e[u].size();
  16.  
  17.     if (u != 1) --nodeCnt; // excluding parent from count
  18.  
  19.     if (nodeCnt == 0) return 0; // lead node
  20.    
  21.  
  22.     double ret = 0;
  23.  
  24.     for (auto v: e[u]) {
  25.         if (v.first == parent) continue;
  26.         ret += (v.second * dfs(v.first, u, snk, visited, dp, e));
  27.     }
  28.  
  29.     return dp[u] = ret/nodeCnt;
  30. }
  31.  
  32. double solve(const int n, const vector<vector<pair<int, double>>> & e) {
  33.  
  34.     vector<bool> visited (n+1, false);
  35.     vector <double> dp (n+1, -1);
  36.  
  37.  
  38.     return dfs(1, 0, n, visited, dp, e);
  39. }
  40.  
  41. int main() {
  42.    
  43.     freopen("./data/input01.txt", "r", stdin);
  44.     int t;
  45.     cin >> t;
  46.  
  47.     assert (t >= 1 && t <= 10);
  48.  
  49.     for (int ca = 1; ca <= t; ca ++) {
  50.         int n, e;
  51.         cin >> n >> e;
  52.  
  53.  
  54.         assert (n >= 1 && n <= 50);
  55.  
  56.         assert (e >= n-1);
  57.  
  58.         assert (e <= (n*(n-1))/2);
  59.  
  60.         vector<vector<pair<int, double> > > edges (n+1);
  61.  
  62.         map<pair<int, int>, bool> dupcheck;
  63.  
  64.         for (int i = 0; i < e; i ++) {
  65.             int u, v;
  66.             double p;
  67.             cin >> u >> v >> p;
  68.  
  69.  
  70.             if (u > v) swap(u, v);
  71.  
  72.             assert (u != v);
  73.  
  74.             if (dupcheck[{u, v}]) {
  75.                 cerr << "{" << u << ", " << v << "} duplicate\n";
  76.                 assert (false);
  77.             }
  78.  
  79.             dupcheck[{u, v}] = true;
  80.  
  81.             edges[u].emplace_back(v, p);
  82.             edges[v].emplace_back(u, p);
  83.         }
  84.        
  85.         double ans = 1/solve(n, edges);
  86.         cout << fixed << setprecision(6) << ans<< endl;
  87.     }
  88.  
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement