#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
#define maxn 1005
struct node{
int x,y,z;
}n1;
int p[maxn];
int n,m;
vector<struct node>vec;
bool cmp(struct node n2,struct node n3)
{
return n2.z < n3.z;
}
int find(int x)
{
if(p[x] == x)
{
return x;
}else{
int y=find(p[x]);
p[x] = y;
return y;
}
}
void union_p(int x,int y)
{
if(x==y)
{
return ;
}
p[x] = y;
}
int main()
{
int x,y,z;
cin >> n >> m;
for(int i=0;i<m;i++)
{
cin >> x >> y >> z;
n1.x=x,n1.y=y,n1.z=z;
vec.push_back(n1);
}
sort(vec.begin(),vec.end(),cmp);
for(int i=1;i<=n;i++)
{
p[i]=i;
}
int i=0;
int ans=0;
int k=0;
while(i<m)
{
x=vec[i].x,y=vec[i].y,z=vec[i].z;
int xf = find(x);
int yf = find(y);
if(xf!=yf){
union_p(xf,yf);
ans=ans+z;
k++;
}
if(k==n-1){
break;
}
i++;
}
cout << ans << endl;
return 0;
}
prime算法模板
#include<bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
int lowcost[1010];
int e[1010][1010];
bool vis[1010];
int n,m,sum;
void prime()
{
vis[1]=1;
int tmp;
int k;
for(int i=1;i<=n;i++)
lowcost[i]=e[1][i];
for(int i=1;i<n;i++)
{
tmp=INF;
for(int j=1;j<=n;j++)
if(!vis[j]&&lowcost[j]<tmp)
tmp=lowcost[k=j];
sum+=tmp;
vis[k]=1;
for(int j=1;j<=n;j++)
if(!vis[j]&&lowcost[j]>e[k][j])
lowcost[j]=e[k][j];
}
}
int main()
{
int u,v,c;
scanf("%d %d",&n,&m);
memset(e,INF,sizeof(e));
for(int i=0;i<m;i++)
{
scanf("%d %d %d",&u,&v,&c);
e[u][v]=c;
e[v][u]=c;
}
prime();
printf("%d\n",sum);
}