就这个Prim爽!
2024-10-02 16:20:09
发布于:广东
41阅读
0回复
0点赞
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
#include <memory.h>
#define double pair <int, int>
using namespace std;
vector <double> v[5005];
bool vis[5005];
int n, m, x, y, z;
int prim(){
int ct = 0, ctt = 0;
priority_queue <double, vector <double>, greater <double>> q;
q.push({0, 1});
while(!q.empty()){
double head = q.top();
q.pop();
if(vis[head.second]) continue;
vis[head.second] = 1, ctt++, ct += head.first;
for(double it:v[head.second]){
if(!vis[it.first]) q.push({it.second, it.first});
}
}
return (ctt < n ? -1 : ct);
}
int read(){
char c = getchar();
int x = 0, f = 1;
while(!isdigit(c)){
if(c == '-') f = -f;
c = getchar();
}
while(isdigit(c)){
x = (x << 3) + (x << 1) + c - '0';
c = getchar();
}
return x * f;
}
int main(){
n = read(), m = read();
for(int i = 1; i <= m; i++){
x = read(), y = read(), z = read();
v[x].push_back({y, z}), v[y].push_back({x, z});
}
int ans = prim();
if(ans == -1) cout << "orz";
else cout << ans;
return 0;
}
这里空空如也
有帮助,赞一个