标签:prim 生成 print int 最小生成树 ++ return main for
题目链接:https://vjudge.net/problem/POJ-1258
思路:
最小生成树板子题。
1 #include <stdio.h> 2 #include <iostream> 3 #include <algorithm> 4 #include <queue> 5 using namespace std; 6 const int N = (int)1e3; 7 const int inf = (int)1e9; 8 int g[N][N]; 9 int dis[N]; 10 bool vis[N]; 11 int n; 12 13 struct node{ 14 int loc; 15 int w; 16 17 bool friend operator<(const node& a,const node& b){ 18 return a.w > b.w; 19 } 20 }; 21 22 priority_queue<node > que; 23 24 int prime(){ 25 26 for(int i = 1; i <= n; i++){ 27 vis[i] = 0; 28 dis[i] = inf; 29 } 30 31 while(!que.empty()) que.pop(); 32 33 que.push(node{1,0}); 34 dis[1] = 0; 35 36 while(!que.empty()){ 37 int u = que.top().loc; 38 que.pop(); 39 vis[u] = 1; 40 41 for(int v = 1; v <= n ; v++){ 42 if(!vis[v] && dis[v] > g[u][v]){ 43 dis[v] = g[u][v]; 44 que.push(node{v,dis[v]}); 45 } 46 } 47 } 48 49 int ans = 0; 50 for(int i = 1; i <= n; i++) 51 ans += dis[i]; 52 53 return ans; 54 } 55 56 int main(){ 57 58 while(~scanf("%d",&n) && n){ 59 60 for(int i = 1; i <= n; i++) 61 for(int j = 1; j <= n; j++) 62 scanf("%d",&g[i][j]); 63 64 printf("%d\n",prime()); 65 } 66 67 return 0; 68 }
标签:prim 生成 print int 最小生成树 ++ return main for
原文地址:https://www.cnblogs.com/SSummerZzz/p/11823030.html