---
id: 1494
lang: en
translation_of: index.md
source_sha256: 8cf63d8c0309cc9e182a6c35595e85daec7030262c8865c4850bf2eeed07be82
title: "P3317: [SDOI2014] Rebuild — Solution"
description: "Applying the Matrix-Tree theorem: just change the matrix entries to p_e/(1 - p_e)."
tags: ["OI","Trees","Spanning Tree","Matrix-Tree Theorem","Adjacency Matrix"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "积和式 rendered as “the products and sums” (the author means merging the product and the sum), not the matrix permanent."
---

## Applying the Matrix-Tree Theorem

Normally, with the Matrix-Tree theorem, what we're really computing is this:

$$
\sum_T  \prod_{e \in T} p_e, \forall p_e = 1
$$

What we're computing is really just the case where all probabilities are $0/1$. Now we need to compute:

$$
\sum_T \prod_{e \in T} p_e \prod_{e \notin T} (1-p_e)
$$

We can try writing it as an expression where the part inside the sum depends only on the matrix:

$$
\sum_T \prod_{e \in T} p_e \frac{ \prod_e (1 - p_e) }{\prod_{e \in T} (1-p_e) }
$$

Merge the products and sums:

$$
\prod_e p_e \sum_T \prod_{e \in T} \frac{p_e}{1 - p_e}
$$

Then we just change the matrix entries to $\frac{p_e}{1 - p_e}$ and we're done.

<!--more-->

## Code

```cpp
// P3317.cpp
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 55;
const double eps = 1e-8;

int n;
double matrix[MAX_N][MAX_N], ans = 1;

void solve()
{
    for (int i = 1; i < n; i++)
    {
        int mx = i;
        for (int j = i + 1; j < n; j++)
            if (fabs(matrix[j][i]) > fabs(matrix[mx][i]))
                mx = j;
        if (mx != i)
            for (int j = 1; j < n; j++)
                swap(matrix[i][j], matrix[mx][j]);
        for (int k = i + 1; k < n; k++)
        {
            double rate = matrix[k][i] / matrix[i][i];
            for (int j = i; j < n; j++)
                matrix[k][j] -= matrix[i][j] * rate;
        }
        if (fabs(matrix[i][i]) < 0)
            return (void)(ans = 0);
    }
    for (int i = 1; i < n; i++)
        ans *= matrix[i][i];
    ans = fabs(ans);
}

int main()
{
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
            scanf("%lf", &matrix[i][j]);
    double tmp = 1;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
        {
            if (matrix[i][j] < eps)
                matrix[i][j] = eps;
            if (1.0 - matrix[i][j] < eps)
                matrix[i][j] = 1.0 - eps;
            if (i < j)
                tmp *= 1.0 - matrix[i][j];
            matrix[i][j] /= (1.0 - matrix[i][j]);
        }
    for (int i = 1; i <= n; i++)
    {
        matrix[i][i] = 0;
        for (int j = 1; j <= n; j++)
            if (i != j)
                matrix[i][i] -= matrix[i][j];
    }
    solve();
    ans *= tmp;
    printf("%.10lf", ans);
    return 0;
}
```
