我偏用最小生成树
2025-09-24 19:08:32
发布于:上海
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
struct edge{
int to,w;
bool operator>(const edge o) const{
return w > o.w;
}
};
int n,m;
vector<vector<edge>> mp;
vector<bool> vis;
priority_queue<edge,vector<edge>,greater<edge>> q;
int main(){
cin >> n >> m;
mp.resize(n + 5);
vis.resize(n + 5,0);
while(m--){
int u,v,w;
cin >> u >> v >> w;
mp[u].push_back({v,w});
mp[v].push_back({u,w});
}
int cnt = 0,ans = 0;
q.push({1,0});
//vis[1] = 1;这行千万不要加!!!!!!!!!!!!!
while(!q.empty()){
edge r = q.top();
q.pop();
if(vis[r.to]) continue;
vis[r.to] = 1;
ans = max(ans,r.w);
cnt++;
for(auto next : mp[r.to]){
if(!vis[next.to]) q.push(next);
}
}
if(cnt == n) cout << ans;
else cout << "-1";
return 0;
}
这里空空如也







有帮助,赞一个