zoukankan      html  css  js  c++  java
  • prim

     1 int n;
     2 int weight;
     3 int g[MAXN][MAXN];
     4 int vis[MAXN];
     5 int dis[MAXN];
     6 
     7 
     8 void prim(int v0){
     9     int pos = v0;
    10     for(int i = 1; i <= n; i++){
    11         dis[i] = g[v0][i];
    12     }
    13     vis[pos] = 1;
    14     for(int i = 1; i < n; i++){
    15         int mins = INF;
    16         for(int j = 1; j <= n; j++){
    17             if(!vis[j] && dis[j] < mins){
    18                 pos = j;
    19                 mins = dis[j];
    20             }
    21         }
    22         weight += mins;
    23         vis[pos] = 1;
    24         for(int j = 1; j <= n; j++){
    25             if(!vis[j] && g[pos][j] < dis[j]){
    26                 dis[j] = g[pos][j];
    27             }
    28         }
    29     }
    30 }
     1 #include <iostream>
     2 #include <queue>
     3 #include <string.h>
     4 using namespace std;
     5 #define M 1000
     6 int g[M][M];
     7 int n, cnt;
     8 int node[M];
     9 int weight;
    10 
    11 void init(){
    12     memset(g,0,sizeof(g));
    13     memset(node,0,sizeof(node));
    14 }
    15 
    16 struct Edge{
    17     int from,to,w;
    18 };
    19 
    20 bool operator < (const Edge &a, const Edge &b){
    21     return a.w > b.w;
    22 }
    23 
    24 int prim(int start){
    25     node[start] = 1;
    26     priority_queue<Edge> q;
    27     for(int i = 0; i < n; i++){
    28         if(0 != g[start][i]){
    29             Edge e;
    30             e.from = start;
    31             e.to = i;
    32             e.w = g[start][i];
    33             q.push(e);
    34         }
    35     }
    36     while(!q.empty()){
    37         Edge cmp = q.top();
    38         q.pop();
    39         if(node[cmp.from] == 0 || node[cmp.to] == 0){
    40             node[cmp.from] = node[cmp.to] = 1;
    41             weight += cmp.w;
    42         }
    43         for(int i = 0; i < n; i++){
    44             if(node[i] == 0 && g[cmp.to][i] != 0){
    45                 Edge add;
    46                 add.from = cmp.to;
    47                 add.to = i;
    48                 add.w = g[cmp.to][i];
    49                 q.push(add);
    50             }
    51         }
    52     }
    53 }
    54 int main(){
    55     init();
    56     cin >> n >> cnt;
    57     for(int i = 0; i < cnt; i++){
    58         int a, b, w;
    59         cin >> a >> b >> w;
    60         g[a][b] = g[b][a] = w;
    61     }
    62     prim(0);
    63     cout << weight << endl;
    64     return 0;
    65 }
  • 相关阅读:
    laravel5.5源码笔记(二、服务提供者provider)
    laravel5.5源码笔记(一、入口应用的初始化)
    laravel5.5源码阅读草稿——路由
    laravel5.5源码阅读草稿——application
    NOIP2018提高组爆炸记
    复习3-数据结构模板
    复习2-数论模板
    复习1-图论模板
    洛谷P3960 列队
    poj3159 Candies
  • 原文地址:https://www.cnblogs.com/jxust-jiege666/p/6832890.html
Copyright © 2011-2022 走看看