kruscal常用:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
using namespace std;
struct node
{
int u, v, w;
} e[10001];
bool cmp(node a, node b)
{
return a.w < b.w;
}
int f[101];
int getf(int u)
{
if (u == f[u])
return u;
return f[u] = getf(f[u]);
}
// 以后就用非递归的 !!!!!!!!!!!!!!!
inline int Getf(int u)
{
if (u == f[u])
return u;
int fa = u;
while (fa != f[fa])
fa = f[fa];
while (u != fa) {
int t = f[u];
f[u] = fa;
u = t;
}
return fa;
}
bool merge(int u, int v)
{
int t1 = getf(u), t2 = getf(v);
if (t1 != t2)
{
f[t2] = t1;
return 1;
}
return 0;
}
int main()
{
int n, m;
while (~scanf("%d %d", &n, &m))
{
int i;
for (i = 0; i < m; i++)
scanf("%d %d %d", &e[i].u, &e[i].v, &e[i].w);
for (i = 1; i <= n; i++)
f[i] = i;
sort(e, e + m, cmp);
int ans = 0, cnt = 0;
for (i = 0; i < m; i++)
{
if (merge(e[i].u, e[i].v))
{
ans += e[i].w;
cnt++;
}
if (cnt == n - 1)
break;
}
printf("%d\n", ans);
}
return 0;
}
prim算法(没优化)
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#define inf 0x3f3f3f3f
using namespace std;
int main()
{
int n, m;
while (~scanf("%d %d", &n, &m))
{
int e[105][105], dis[105] = {0}, book[105] = {0};
int i;
for (i = 1; i <= n; i++)
{
int j;
for (j = 1; j <= n; j++)
{
if (i == j)
e[i][j] = 0;
else
e[i][j] = inf;
}
}
while (m--)
{
int u, v, w;
scanf("%d %d %d", &u, &v, &w);
if (w < e[u][v])
e[u][v] = e[v][u] = w;
}
book[1] = 1;
dis[1] = 0;
int sum = 0;
for (i = 2; i <= n; i++)
dis[i] = e[1][i];
for (i = 1; i <= n; i++)
{
int mmin = inf, k = 1, j;
for (j = 1; j <= n; j++)
{
if (book[j] == 0 && dis[j] < mmin)
{
mmin = dis[j];
k = j;
}
}
book[k] = 1;
sum += dis[k];
for (j = 1; j <= n; j++)
{
if (book[j] == 0)
{
if (dis[j] > e[k][j])
dis[j] = e[k][j];
}
}
}
printf("%d\n", sum);
}
return 0;
}
优化就是dijkstra的优化