题目链接(板子题)
#include <bits/stdc++.h>
using namespace std;
#define NewNode (ListNode *)malloc(sizeof(ListNode))
#define Mem(a,b) memset(a,b,sizeof(a))
const int N = 2e5 + 50;
const int INF = 0x3f3f3f3f;
const double EPS = 1e-10;
const unsigned long long mod = 998244353;
const int II = 3.1415926535;
typedef long long ll;
typedef unsigned long long ull;
struct node
{
int z;
int val;
int Next;
}Node[2*N];
int Head[N],vis[N],m,n,k,ans,sum,dis[N];
void Add(int a,int b,int c)
{
m++;
Node[m].z = b;
Node[m].val = c;
Node[m].Next = Head[a];
Head[a] = m;
}
void Prim()
{
int now = 1;
fill(dis+1,dis+N,INF);
for(int i = Head[1];i;i = Node[i].Next)
dis[Node[i].z] = min(dis[Node[i].z],Node[i].val);
while(++ans < n)
{
// cout << sum << " " << now << endl;
vis[now] = 1;
int Min = INF;
for(int i = 1;i <= n;i++)
if(!vis[i] && Min > dis[i])
Min = dis[i],now = i;
sum += Min;
for(int i = Head[now];i;i = Node[i].Next)
if(!vis[Node[i].z])
dis[Node[i].z] = min(dis[Node[i].z],Node[i].val);
}
}
int main()
{
std::ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
cin >> n >> k;
for(int i = 0;i < k;i++)
{
int a,b,c;
cin >> a >> b >> c;
Add(a,b,c);
Add(b,a,c);
}
Prim();
cout << sum << endl;
}