prim:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int INF = 0x3f3f3f3f;
const int Max = 1e3;
int mp[Max][Max],micost[Max],vis[Max];
int V,E;
int prim()
{
for(int i=1;i<=V;i++)
{
micost[i]=mp[1][i];
vis[i]=0;
}
vis[1]=1;
int res = 0;
for(int i=1;i<=V;i++)
{
int mi = INF,k = -1;
for(int j=1;j<=V;j++)
{
if(!vis[j]&&mi>micost[j]){
mi = micost[j];
k = j;
}
}
if(k==-1) break;
vis[k]=1;
res += micost[k];
for(int j=1;j<=V;j++)
{
if(!vis[j]&&micost[j]>mp[k][j])
micost[j]=mp[k][j];
}
}
return res;
}
int main()
{
int from,to,cost;
cin>>V>>E;
for(int i=1;i<=V;i++)
for(int j=1;j<=V;j++)
mp[i][j]=(i==j?0:INF);
for(int i=0;i<E;i++)
{
cin>>from>>to>>cost;
mp[from][to]=cost;
mp[to][from]=cost;//不要忘记了
}
int ans = prim();
cout<<ans<<endl;
return 0;
}
Kruskal:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int Max = 1e3;
const int INF = 0x3f3f3f3f;
struct node{
int from,to,ed;
};
node no[Max];
int V,E;
int par[Max];
int cmp(node e1,node e2)
{
return e1.ed<e2.ed;
}
void init()
{
for(int i=1;i<=V;i++)
par[i]=i;
}
int find(int x)
{
if(x==par[x]) return x;
else return par[x]=find(par[x]);
}
void unite(int x,int y)
{
x = find(x);
y = find(y);
if(x!=y)
par[x]=y;
}
int Kruskal()
{
sort(no,no+E,cmp);
init();
int res = 0;
for(int i=0;i<E;i++)
{
node e = no[i];
if(find(e.from)!=find(e.to)){
unite(e.from,e.to);
res += e.ed;
}
}
return res;
}
int main()
{
cin>>V>>E;
for(int i=0;i<E;i++)
cin>>no[i].from>>no[i].to>>no[i].ed;
int ans = Kruskal();
cout<<ans<<endl;
return 0;
}