prim算法
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e2;
const int INF = 1<<30;
int g[maxn][maxn];
int n;
struct edge{
int v;
int w;
};
void init(){
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++)g[i][j]=INF;
}
}
void prim(int v=1){
bool reach[maxn]={false};
edge e[maxn];
for(int i=1;i<=n;i++){
e[i].v=v;
e[i].w=g[v][i];
}
reach[v]=true;
while(true){
int Min=INF,index=-1;
for(int i=1;i<=n;i++)if(!reach[i]&&Min>e[i].w)Min=e[i].w,index=i;
if(index==-1)return ;
cout<<e[index].v<<"-->"<<index<<endl;
reach[index]=true;
for(int i=1;i<=n;i++){
if(!reach[i]&&g[index][i]<e[i].w){
e[i].w=g[index][i];
e[i].v=index;
}
}
}
}
int main(){
int m;
int a,b,c;
scanf("%d%d",&n,&m);
init();
for(int i=0;i<m;i++){
scanf("%d%d%d",&a,&b,&c);
g[a][b]=g[b][a]=c;
}
prim(1);
}
测试输入
7 9
1 2 28
1 6 10
2 3 16
2 7 14
3 4 12
4 5 22
4 7 18
5 6 25
5 7 24
输出
1-->6
6-->5
5-->4
4-->3
3-->2
2-->7
Kruskal算法
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e2;
const int INF = 1<<30;
int g[maxn][maxn];
int n;
int f[maxn];
struct edge{
int v1,v2;
int w;
bool operator<(const edge& a) const
{
return w > a.w;
}
edge(int a,int b,int c):v1(a),v2(b),w(c){}
};
void init(){
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++)g[i][j]=INF;
}
}
int find(int x){
return x==f[x]?x:f[x]=find(f[x]);
}
void kruskal(int v=1){
for(int i=1;i<=n;i++)f[i]=i;
priority_queue<edge>p;
for(int i=2;i<=n;i++){
for(int j=1;j<i;j++){
int w = g[i][j];
if(w!=INF)p.push(edge(i,j,w));
}
}
while(!p.empty()){
edge e =p.top();
p.pop();
int xx=find(e.v1),yy=find(e.v2);
if(xx==yy)continue;
cout<<e.v1<<"-->"<<e.v2<<endl;
f[xx]=yy;
}
}
int main(){
int m;
int a,b,c;
scanf("%d%d",&n,&m);
init();
for(int i=0;i<m;i++){
scanf("%d%d%d",&a,&b,&c);
g[a][b]=g[b][a]=c;
}
kruskal(1);
}
测试输出
6-->1
4-->3
7-->2
3-->2
5-->4
6-->5