AcWing 1140. 最短网络
原题链接
简单
作者:
minux
,
2020-06-20 16:24:19
,
所有人可见
,
阅读 442
c++堆优化Prim
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> PII;
#define fi first
#define se second
const int N=105;
int n;
int g[N][N];
bool vis[N];
int dist[N];
int prim(){
priority_queue<PII, vector<PII>, greater<PII>> q;
int ans=0;
dist[1]=0;
q.push({dist[1], 1});
while(!q.empty()){
int node=q.top().se;
q.pop();
if(vis[node]) continue;
vis[node]=true;
ans+=dist[node];
for(int i=1; i<=n; ++i){
if(dist[i]>g[node][i]){
dist[i]=g[node][i];
q.push({dist[i], i});
}
}
}
return ans;
}
int main(){
memset(vis, 0x00, sizeof vis);
memset(dist, 0x3f, sizeof dist);
cin>>n;
for(int i=1; i<=n; ++i)
for(int j=1; j<=n; ++j)
cin>>g[i][j];
cout<<prim()<<endl;
return 0;
}