Kruskal
#include<bits/stdc++.h>
using namespace std;
const int MAXV = 1e5+5;
const int MAXE = 5e5+5;
struct Edge{
int u,v;
int cost;
bool operator < (const Edge &r)const{
return cost < r.cost;
}
Edge(){}
Edge(int &u, int &v) : u(u),v(v) {}
}E[MAXE];
bool cmp(Edge a,Edge b){
return a.cost < b.cost;
}
int Father[MAXV];
int findFA(int x){
int a = x;
while(x != Father[x]){
x = Father[x];
}
while(a != Father[a]){
int z = a;
a = Father[a];
Father[z] = x;
}
return x;
}
int kruskal(int m,int n){
int ans = 0,edgenum = 0;
for(int i = 1; i <= m; i++){
Father[i] = i;
}
sort(E + 1, E + n + 1, cmp);
for(int i = 1; i <= n; i++){
int fau = findFA(E[i].u);
int fav = findFA(E[i].v);
if(fau != fav){
Father[fau] = fav;
ans += E[i].cost;
edgenum++;
}
if(edgenum == m - 1) break;
}
return ans;
}
int main(){
int m,n;
scanf("%d%d",&m,&n);
for(int i = 1; i <= n; i++){
scanf("%d%d%d",&E[i].u,&E[i].v,&E[i].cost);
}
int ans = kruskal(m,n);
printf("%d\n",ans);
}
Prime
#include<bits/stdc++.h>
using namespace std;
const int maxv = 1e5+5;
const int inf = 1000000000;
struct Node{
int v,dis;
Node(){}
Node(int v,int dis) : v(v),dis(dis){}
bool operator <(const Node &a)const{
return dis < a.dis;
}
};
vector<Node> node[maxv];
int dis[maxv];
bool vis[maxv] = {false};
int prime(int m,int n){
fill(dis,dis+maxv,inf);
dis[1] = 0;
int ans = 0;
for(int i = 0; i < m; i++){
int u = -1,Min = inf;
for(int j = 1; j <= m; j++){
if(!vis[j] && dis[j] < Min){
u = j;
Min = dis[j];
}
}
vis[u] = true;
ans += dis[u];
for(int j = 0; j < node[u].size(); j++){
int v = node[u][j].v;
if(!vis[v] && dis[v] > node[u][j].dis){
dis[v] = node[u][j].dis;
}
}
}
return ans;
}
int main(){
int m,n;
int u,v,w;
scanf("%d%d",&m,&n);
for(int i = 0; i < n; i++){
scanf("%d%d%d",&u,&v,&w);
node[u].push_back(Node(v,w));
node[v].push_back(Node(u,w));
}
int ans = prime(m, n);
printf("%d\n",ans);
}
Prime+堆优化
#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> par;
const int maxv = 1e5+5;
const int inf = 1000000000;
struct Node{
int v,dis;
Node(){}
Node(int v,int dis) : v(v),dis(dis){}
bool operator <(const Node &a)const{
return dis > a.dis;
}
};
vector<Node> node[maxv];
int dis[maxv];
bool vis[maxv] = {false};
priority_queue<Node> q;
int prime(int m,int n){
fill(dis,dis+maxv,inf);
dis[1] = 0;
q.push(Node(1,0));
Node st;
int ans = 0;
while(!q.empty()){
st = q.top();q.pop();
if(vis[st.v]) continue;
vis[st.v] = true;
ans += st.dis;
for(int j = 0; j < node[st.v].size(); j++){
int v = node[st.v][j].v;
if(!vis[v] && dis[v] > node[st.v][j].dis){
dis[v] = node[st.v][j].dis;
q.push(Node(v,dis[v]));
}
}
}
return ans;
}
int main(){
int m,n;
int u,v,w;
scanf("%d%d",&m,&n);
for(int i = 0; i < n; i++){
scanf("%d%d%d",&u,&v,&w);
node[u].push_back(Node(v,w));
node[v].push_back(Node(u,w));
}
int ans = prime(m, n);
printf("%d\n",ans);
}