1. 程式人生 > >Minimum Spanning Tree(prim()演算法)

Minimum Spanning Tree(prim()演算法)

滴答滴答---題目連結 

For a given weighted graph $G = (V, E)$, find the minimum spanning tree (MST) of $G$ and print total weight of edges belong to the MST.

Input

In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, a $n \times n$ adjacency matrix $A$ which represents $G$ is given. $a_{ij}$ denotes the weight of edge connecting vertex $i$ and vertex $j$. If there is no edge between $i$ and $j$, $a_{ij}$ is given by -1.

Output

Print the total weight of the minimum spanning tree of $G$.

Constraints

  • $1 \leq n \leq 100$
  • $0 \leq a_{ij} \leq 2,000$ (if $a_{ij} \neq -1$)
  • $a_{ij} = a_{ji}$
  • $G$ is a connected graph

Sample Input 1

5
 -1 2 3 1 -1
 2 -1 -1 4 -1
 3 -1 -1 1 1
 1 4 1 -1 3
 -1 -1 1 3 -1

Sample Output 1

5

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.

#include <iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
const int maxn=101;
const int inf=0x3f3f3f;
int n;
int e[maxn][maxn];
int b[maxn];//權值最小的邊權
int p[maxn];//標記v父親結點
int vis[maxn];//訪問狀態
int prim()
{
    memset(vis,0,sizeof(vis));
    memset(p,-1,sizeof(p));
    for(int i=0; i<n; i++)
        b[i]=inf;
    b[0]=0;//選0為起點
    while(1)
    {
        int v=-1;
        int ans=inf;
        for(int i=0; i<n; i++)
        {
            if(!vis[i]&&ans>b[i])
            {
                v=i;
                ans=b[i];
            }
        }
        if(v==-1)
            break;
        vis[v]=1;
        for(int i=0; i<n; i++)
        {
            if(!vis[i]&&b[i]>e[v][i]&&e[v][i]!=inf)
            {
                b[i]=e[v][i];
                p[i]=v;
            }
        }
    }
    int ans=0;
    for(int i=0; i<n; i++)
    {
        if(p[i]!=-1)
            ans+=e[i][p[i]];
    }
    return ans;
}

int main()
{
    scanf("%d",&n);
    for(int i=0; i<n; i++)
        for(int j=0; j<n; j++)
        {
            int a;
            cin>>a;
            if(a!=-1)
                e[i][j]=a;
            else e[i][j]=inf;
        }
    printf("%d\n",prim());
    return 0;
}