//Prim
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
int Edge[10010][10010];
bool vis[10010];
int dis[10010];
void Prim();
int n, m;
int main()
{
while(cin >> n >> m)
{
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
(i == j) ? Edge[i][j] = 0 : Edge[i][j] = INF;
}
for(int i = 1; i <= m; i++)
{
int u, v, w;
cin >> u >> v >> w;
Edge[u][v] = Edge[v][u] = w;
}
Prim();
}
return 0;
}
void Prim()
{
int num = 0;
memset(vis, 0, sizeof(vis));
for(int i = 1; i <= n; i++)
{
dis[i] = Edge[1][i];
}
vis[1] = 1;
for(int i = 1; i < n; i++)
{
int tmp = INF;
int pos;
for(int j = 1; j <= n; j++)
{
if(!vis[j] && dis[j] < tmp)
{
tmp = dis[pos = j];
}
}
vis[pos] = 1;
if(tmp == INF)
break;
num += tmp;
for(int j = 1; j <= n; j++)
{
if(!vis[j] && Edge[pos][j] < dis[j])
{
dis[j] = Edge[pos][j];
}
}
}
cout << num << endl;
}
//Kruskal
#include <bits/stdc++.h>
using namespace std;
struct edge
{
int u, v, w;
} Edge[10010];
int n, m;
int pre[10010];
int Find(int x);
int join(int x, int y);
void kruskal();
int cmp(edge a, edge b)
{
return a.w < b.w;
}
int main()
{
while(cin >> n >> m)
{
for(int i = 1; i <= m; i++)
{
int u, v, w;
cin >> u >> v >> w;
Edge[i].u = u;
Edge[i].v = v;
Edge[i].w = w;
}
sort(Edge+1, Edge+m+1, cmp);
kruskal();
}
return 0;
}
int Find(int x)
{
int r = x;
while(pre[r] != r)
r = pre[r];
int i = x, j;
while(i != r)//路径压缩
{
j = pre[i];
pre[i] = r;
i = j;
}
return r;
}
int join(int x, int y)
{
int fx = Find(x), fy = Find(y);
if(fx != fy)
{
pre[fx] = fy;
}
}
void kruskal()
{
int sumweight = 0;
int num = 0;
int u, v;
for(int i = 1; i <= n; i++)
{
pre[i] = i;
}
for(int i = 1; i <= m; i++)
{
u = Edge[i].u, v = Edge[i].v;
if(Find(u) != Find(v))
{
num++;
sumweight += Edge[i].w;
join(u, v);
}
if(num == n-1)
{
break;
}
}
cout << sumweight << endl;
}
SUDT 2144 图结构练习——最小生成树
最新推荐文章于 2018-07-28 15:42:40 发布