裸的模板题 因为直接用的邻接矩阵所以用最小值覆盖先前输入的重复边

#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>
#define INF 0x3F3F3F3F
using namespace std; typedef pair<int, int> pii;
struct cmp{
bool operator () (const pii a, const pii b){
return a.first > b.first;
}
}; int n, m, val[][]; int prim(int s)
{
int ans = , dist[], vis[];
memset(dist, 0x3f, sizeof dist);
memset(vis, false, sizeof vis); priority_queue<pii, vector<pii>, cmp> q;
for(int i = ; i <= n; i++){
if(val[s][i] != INF){
dist[i] = val[s][i];
q.push(make_pair(dist[i], i));
}
}
dist[s] = ;
vis[s] = true;
while(!q.empty()){
pii u = q.top();
q.pop();
if(vis[u.second]) continue;
vis[u.second] = true;
ans += u.first;
for(int i = ; i <= n; i++){
if(!vis[i] && dist[i] > val[u.second][i]){
dist[i] = val[u.second][i];
q.push(make_pair(dist[i], i));
}
}
}
return ans;
}
int main()
{
while(scanf("%d%d", &n, &m) == ){
int u, v, w;
memset(val, 0x3f, sizeof val);
while(m--){
scanf("%d%d%d", &u, &v, &w);
val[u][v] = val[v][u] = min(val[u][v], w);
}
printf("%d\n", prim());
}
return ;
}
04-28 11:15