题目来源:http://poj.org/problem?id=1258
最小生成树,Kruskal,Prim;
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 110;
const int MAXM = 10010;
const int INF = 10000000;
int n, m;
int kcount[MAXN];
int parent[MAXN];
struct Node
{
int u, v;
int cost;
Node()
{
u = v = cost = 0;
}
}Map[MAXM];
int cmp(const void* a, const void *b)
{
Node* aa = (Node*)a;
Node* bb = (Node*)b;
return aa->cost - bb->cost;
}
void UFset()
{
int i;
for(i = 1; i <= n; ++i)
{
parent[i] = i;
kcount[i] = 1;
}
}
int Find(int x)
{
if(x != parent[x])
parent[x] = Find(parent[x]);
return parent[x];
}
void Union(int x, int y)
{
int r1 = Find(x);
int r2 = Find(y);
if(kcount[r1] > kcount[r2])
{
parent[r2] = r1;
kcount[r1] += kcount[r2];
}
else
{
parent[r1] = r2;
kcount[r2] += kcount[r1];
}
}
void Kruskal()
{
int sumweight = 0;
UFset();
for(int i = 1; i <= m; ++i)
{
if(Find(Map[i].u) != Find(Map[i].v))
{
sumweight += Map[i].cost;
Union(Map[i].u, Map[i].v);
}
}
printf("%d\n", sumweight);
}
int main()
{
int i, j;
int cost;
while(~scanf("%d", &n))
{
m = 1;
for(i = 1; i <= n; ++i)
{
for(j = 1; j <= n; ++j)
{
scanf("%d", &cost);
if(i < j)
{
Map[m].cost = cost;
Map[m].u = i;
Map[m++].v = j;
}
}
}
//sort(Map, Map+m, cmp);
qsort(Map, m, sizeof(Map[0]), cmp);
Kruskal();
}
return 0;
}
Prim
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int MAXN = 110;
const int INF = 10000000;
int Graph[MAXN][MAXN];
int n;
void Prim(int u)
{
int i, j, k, v, Min_Weight;
int lowcost[MAXN];
int sumweight = 0;
memset(lowcost, 0, sizeof(lowcost));
for(i = 0; i < n; ++i)
lowcost[i] = Graph[0][i];
lowcost[u] = -1;
sumweight = 0;
for(i = 1; i < n; ++i)
{
Min_Weight = INF, v = -1;
for(j = 0; j < n; ++j)
{
if(lowcost[j] != -1 && lowcost[j] < Min_Weight)
{
v = j, Min_Weight = lowcost[j];
}
}
if(v != -1)
{
lowcost[v] = -1;
sumweight += Min_Weight;
for(k = 0; k < n; ++k)
{
if(lowcost[k] != -1 && lowcost[k] > Graph[v][k])
lowcost[k] = Graph[v][k];
}
}
}
printf("%d\n", sumweight);
}
int main()
{
int i, j;
while(~scanf("%d", &n))
{
memset(Graph, 0, sizeof(Graph));
for(i = 0; i < n; ++i)
{
for(j = 0; j < n; ++j)
{
scanf("%d", &Graph[i][j]);
if(i == j)
Graph[i][j] = INF;
}
}
Prim(0);
}
return 0;
}