Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- double dfs(const int u, const int parent, const int snk, vector<bool> & visited,vector<double> & dp, const vector<vector<pair<int, double>>> & e) {
- if (u == snk) return 1;
- if (dp[u] != -1) return dp[u]; // visited a processed cousin/sibling
- if (visited[u]) return 0; // visited a grand-parent
- visited[u] = 1;
- int nodeCnt = e[u].size();
- if (u != 1) --nodeCnt; // excluding parent from count
- if (nodeCnt == 0) return 0; // lead node
- double ret = 0;
- for (auto v: e[u]) {
- if (v.first == parent) continue;
- ret += (v.second * dfs(v.first, u, snk, visited, dp, e));
- }
- return dp[u] = ret/nodeCnt;
- }
- double solve(const int n, const vector<vector<pair<int, double>>> & e) {
- vector<bool> visited (n+1, false);
- vector <double> dp (n+1, -1);
- return dfs(1, 0, n, visited, dp, e);
- }
- int main() {
- freopen("./data/input01.txt", "r", stdin);
- int t;
- cin >> t;
- assert (t >= 1 && t <= 10);
- for (int ca = 1; ca <= t; ca ++) {
- int n, e;
- cin >> n >> e;
- assert (n >= 1 && n <= 50);
- assert (e >= n-1);
- assert (e <= (n*(n-1))/2);
- vector<vector<pair<int, double> > > edges (n+1);
- map<pair<int, int>, bool> dupcheck;
- for (int i = 0; i < e; i ++) {
- int u, v;
- double p;
- cin >> u >> v >> p;
- if (u > v) swap(u, v);
- assert (u != v);
- if (dupcheck[{u, v}]) {
- cerr << "{" << u << ", " << v << "} duplicate\n";
- assert (false);
- }
- dupcheck[{u, v}] = true;
- edges[u].emplace_back(v, p);
- edges[v].emplace_back(u, p);
- }
- double ans = 1/solve(n, edges);
- cout << fixed << setprecision(6) << ans<< endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement