无向图 适用于稠密图 时间复杂度O(N^2)
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 510;
bool IsVisit[N];
int Graph[N][N];
int n,m;
int Dis[N];
int Prim()
{
memset(Dis, INF, sizeof(Dis));
int nResult = 0;
for(int i = 0; i < n; i++)
{
int nShort = -1;
for(int j = 1; j <= n; j++)
{
if(!IsVisit[j] && (-1 == nShort || Dis[nShort] > Dis[j]))
{
nShort = j;
}
}
IsVisit[nShort] = true;
if(i && (INF == Dis[nShort]))
{
return INF;
}
if(i)
{
nResult += Dis[nShort];
}
for(int j = 1; j <= n; j++)
{
Dis[j] = min(Dis[j],Graph[nShort][j]);
}
}
return nResult;
}
int main(int argc, char** argv)
{
scanf("%d%d",&n, &m);
memset(Graph, INF, sizeof(Graph));
for(int i = 0; i < m; i++)
{
int nStart,nEnd,nWeight;
scanf("%d%d%d",&nStart, &nEnd, &nWeight);
Graph[nStart][nEnd] = Graph[nEnd][nStart] =
min(Graph[nStart][nEnd], nWeight);
}
int nResult = Prim();
if(INF == nResult)
{
printf("No Tree\n");
}
else
{
printf("%d",nResult);
}
return 0;
}