# 问题

N个点M条边的无向连通图，每条边有一个权值，求该图的最小生成树。

# 题解

## prim 优先队列+邻接链表

//62 ms 3584 KB

#include<stdio.h>
#include<queue>
#include<vector>
#define INF 0x3f3f3f3f
#define MAX_V 1002
#define MAX_E 50002
using namespace std;
typedef pair<int,int> P;//fiest->cost  second->id
struct edge{int to,cost;};
vector<edge> G[MAX_V];
int V,E;
int used[MAX_V];

int prim(){
fill(used,used+V+1,false);
priority_queue<P,vector<P>,greater<P> > que;
que.push({0,1});
int res=0;

while(!que.empty()){
P p=que.top();que.pop();
int v=p.first,f=p.second;
if(used[f]) continue;
used[f]=true;
res+=v;

for(int i=0;i<G[f].size();i++)
if(!used[G[f][i].to])
que.push({G[f][i].cost,G[f][i].to});
}
return res;
}

int main()
{
int x,y,v;
while(~scanf("%d%d",&V,&E)){
for(int i=0;i<E;i++){
scanf("%d%d%d",&x,&y,&v);
G[x].push_back({y,v});
G[y].push_back({x,v});
}
printf("%d\n",prim());
for(int i=1;i<=V;i++) G[i].clear();
}
return 0;
}

## Kruskal

//78 ms 2312 KB

#include<stdio.h>
#include<algorithm>
#define INF 0x3f3f3f3f
#define MAX_V 1002
#define MAX_E 50002
using namespace std;
struct edge{int from,to,cost;};
edge es[MAX_E];
int par[MAX_V];
int E,V;

void init(int n){for(int i=0;i<=n;i++) par[i]=i;}
int find(int x){return x==par[x]?x:par[x]=find(par[x]);}
void unite(int x,int y){par[find(y)]=find(x);}
bool same(int x,int y){return find(x)==find(y);}

bool cmp(edge x,edge y){return x.cost<y.cost;};

int kruskal(){
sort(es,es+E,cmp);
init(V);
int res=0;

for(int i=0;i<E;i++){
int x=es[i].from,y=es[i].to;
if(!same(x,y)){
unite(x,y);
res+=es[i].cost;
}
}
return res;
}

int main()
{
while(~scanf("%d%d",&V,&E)){
for(int i=0;i<E;i++)
scanf("%d%d%d",&es[i].from,&es[i].to,&es[i].cost);
printf("%d\n",kruskal());
}
return 0;
}