Advertisement
bero_0401

Number of spanning trees in a Graph

Jul 11th, 2024
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.96 KB | Source Code | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int N = 4;
  5. // Function to get cofactor of A[p][q] in temp[][]. n is current dimension of A[][]
  6. void getCofactor(int A[N][N], int temp[N][N], int p, int q, int n)
  7. {
  8.     int i = 0, j = 0;
  9.  
  10.     // Looping for each element of the matrix
  11.     for (int row = 0; row < n; row++)
  12.     {
  13.         for (int col = 0; col < n; col++)
  14.         {
  15.             // Copying into temporary matrix only those element which are not in given row and column
  16.             if (row != p && col != q)
  17.             {
  18.                 temp[i][j++] = A[row][col];
  19.  
  20.                 // Row is filled, so increase row index and reset col index
  21.                 if (j == n - 1)
  22.                 {
  23.                     j = 0;
  24.                     i++;
  25.                 }
  26.             }
  27.         }
  28.     }
  29. }
  30. /* Recursive function for finding determinant of matrix. n is current dimension of A[][]. */
  31. int determinant(int A[N][N], int n)
  32. {
  33.     int D = 0; // Initialize result
  34.  
  35.     // Base case : if matrix contains single element
  36.     if (n == 1)
  37.         return A[0][0];
  38.  
  39.     int temp[N][N]; // To store cofactors
  40.     int sign = 1; // To store sign multiplier
  41.  
  42.     // Iterate for each element of first row
  43.     for (int f = 0; f < n; f++)
  44.     {
  45.         // Getting Cofactor of A[0][f]
  46.         getCofactor(A, temp, 0, f, n);
  47.         D += sign * A[0][f] * determinant(temp, n - 1);
  48.  
  49.         // terms are to be added with alternate sign
  50.         sign = -sign;
  51.     }
  52.  
  53.     return D;
  54. }
  55. int main()
  56. {
  57.     int n , m; cin>>n>>m;
  58.     int A[N][N];
  59.     memset(A , 0 , sizeof A);
  60.     for(int i = 0; i<m; i++)
  61.     {
  62.         int v , u; cin>>v>>u;
  63.         u--; v--;
  64.         A[v][u]= A[u][v] = -1;
  65.         A[v][v]++;
  66.         A[u][u]++;
  67.     }
  68.     int copy[N][N];
  69.     for(int i =1; i< n; i++)
  70.     {
  71.         for(int j = 1; j<n; j++)
  72.         {
  73.             copy[i-1][j-1] = A[i][j];
  74.         }
  75.     }
  76.     cout<<determinant(copy,n-1);
  77.  
  78.  
  79.     return 0;
  80. }
  81.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement