#include <bits/stdc++.h>
#define int long long
using namespace std;
struct Edge
{
int to;
int weight;
Edge(int t,int w):to(t),weight(w){}
bool operator>(const Edge& other)const
{
return weight>other.weight;
}
};
vector<vector<Edge>> graph;
int n,m;
int prim()
{
vector<bool> isvisit(n+1,false);
priority_queue<Edge,vector<Edge>,greater<Edge>> pq;
int res=0;
int start=1;
isvisit[start]=true;
for (const Edge& edge:graph[start])
{
pq.push(edge);
}
int sum=1;
while (!pq.empty()&&sum<n)
{
Edge current=pq.top();
pq.pop();
int to=current.to;
if (isvisit[to])
{
continue;
}
isvisit[to]=true;
res+=current.weight;
sum++;
for (const Edge& edge:graph[to])
{
if (!isvisit[edge.to])
{
pq.push(edge);
}
}
}
if (sum<n)
{
return -1;
}
return res;
}
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cin>>n>>m;
graph.resize(n+1);
for (int i=0;i<m;i++)
{
int u,v,w;
cin>>u>>v>>w;
graph[u].emplace_back(v,w);
graph[v].emplace_back(u,w);
}
int ans=prim();
if (ans==-1)
{
cout<<"orz";
}
else
{
cout<<ans;
}
return 0;
}剪贴板
剪贴板 fb8sbml4
剪贴板信息
剪贴板信息
- 收录
- 更新