prime + 邻接矩阵
O(n^2)
//
// main.cpp
// MST板题_hdu1301
//
// Created by 陈冉飞 on 2019/9/23.
// Copyright © 2019 陈冉飞. All rights reserved.
//
#include <iostream>
using namespace std;
#define maxn 30
int mp[maxn][maxn],n,m,l,d[maxn],vis[maxn]; //mp[][]邻接矩阵储存
char s[10],t[10];
#define INF 0x3f3f3f
#include <cstring>
#define cl(a,b) memset(a,b,sizeof(a))
int prime(){
for (int i = 0; i < n; i++) d[i] = mp[0][i];
d[0] = 0;vis[0] = 1;
int ans = 0;
for (int i = 1; i < n; i++) {
int v = -1,tem = INF;
for (int j = 0; j < n; j++)
if (!vis[j] && d[j] < tem) {
v = j;tem = d[j];
}
vis[v] = 1;ans += tem;
for (int j = 1; j < n; j++)
if (!vis[j] && mp[v][j] < d[j]) d[j] = mp[v][j];
}
return ans;
}
int main(int argc, const char * argv[]) {
while (~scanf("%d",&n) && n) {
//init
cl(mp, 0);cl(vis, 0);cl(d, 0);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (i == j) mp[i][j] = 0;
else mp[i][j] = INF;
for (int e = 0; e < n-1; e++) {
scanf("%s%d",s,&m);
while (m--) {
scanf("%s%d",t,&l);
if (mp[s[0]-'A'][t[0]-'A'] > l) mp[s[0]-'A'][t[0]-'A'] = mp[t[0]-'A'][s[0]-'A'] = l;
}
}
// for (int i = 0; i < n; i++){
// for (int j = 0; j < n; j++)
// printf("%d ",mp[i][j]);
// printf("\n");
// }
cout<<prime()<<endl;
}
return 0;
}
kruskal + 邻接表
O(m*logn)
//
// main.cpp
// MST板题hdu1301_Kruskal实现
//
// Created by 陈冉飞 on 2019/9/25.
// Copyright © 2019 陈冉飞. All rights reserved.
//
#include <iostream>
using namespace std;
#include <cstring>
#define cl(a,b) memset(a,b,sizeof(a))
#define maxn 30
#include <algorithm>
struct node{
int s,e,w;
}edge[maxn<<4]; //邻接表储存图中的结构
int fa[maxn],n,m,l,cnt;
char s[10],t[10];
bool cmp(node x,node y){return x.w < y.w;}
int findfa(int x){
if (x != fa[x]) fa[x] = findfa(fa[x]);
return fa[x];
}
int kruskal(){
sort(edge,edge+cnt,cmp);
int ans = 0;
//遍历所有的边
for (int i = 0; i < cnt; i++)
if (findfa(edge[i].s) != findfa(edge[i].e)) {
ans += edge[i].w;
fa[findfa(edge[i].s)] = findfa(edge[i].e);
}
return ans;
}
int main(int argc, const char * argv[]) {
while (~scanf("%d",&n) && n) {
//init
cnt = 0;cl(fa,0);
for (int i = 0; i < n; i++) fa[i] = i;
for (int e = 0; e < n-1; e++) {
scanf("%s%d",s,&m);
while (m--) {
scanf("%s%d",t,&l);
edge[cnt].s = s[0]-'A';
edge[cnt].e = t[0]-'A';
edge[cnt++].w = l;
}
}
// for (int i = 0; i < cnt; i++) cout<<i<<" "<<edge[i].s<<" "<<edge[i].e<<" "<<edge[i].w<<endl;
cout<<kruskal()<<endl;
}
return 0;
}
Poj1679