• 最小生成树 之 CODE[VS] 1078 最小生成树


    /*
      最小生成树
      Prim算法(邻接矩阵)
    */
     1 #include <iostream>
     2 #include <cstdlib>
     3 #include <cstdio>
     4 #include <cstddef>
     5 #include <iterator>
     6 #include <algorithm>
     7 #include <string>
     8 #include <locale>
     9 #include <cmath>
    10 #include <vector>
    11 #include <cstring>
    12 #include <map>
    13 #include <utility>
    14 #include <queue>
    15 #include <stack>
    16 #include <set>
    17 #include <functional>
    18 using namespace std;
    19 typedef pair<int, int> PII; 
    20 const int INF = 0x3f3f3f3f;
    21 const int modPrime = 3046721;
    22 const double eps = 1e-9;
    23 const int MaxN = 110;
    24 const int MaxM = 110;
    25 
    26 int N;
    27 int cost[MaxN][MaxN];
    28 int minCost[MaxN];
    29 bool used[MaxN];
    30 
    31 
    32 void Solve()
    33 {
    34     fill(minCost, minCost + N, INF);
    35     fill(used, used + N, false);
    36     minCost[0] = 0;
    37     int ans = 0;
    38 
    39     while (true)
    40     {
    41         int v = -1;
    42         for (int i = 0; i < N; ++i)
    43         {
    44             if (!used[i] && (-1 == v || minCost[i] < minCost[v]))
    45             {
    46                 v = i;
    47             }
    48         }
    49         if (v == -1)
    50         {
    51             break;
    52         }
    53         used[v] = true;
    54         ans += minCost[v];
    55         for (int i = 0; i < N; ++i)
    56         {
    57             minCost[i] = min(minCost[i], cost[v][i]);
    58         }
    59     }
    60 
    61     printf("%d
    ", ans);
    62 }
    63 
    64 int main()
    65 {
    66 #ifdef HOME
    67     freopen("in", "r", stdin);
    68     //freopen("out", "w", stdout);
    69 #endif
    70 
    71     scanf("%d", &N);
    72     for (int i = 0; i < N; ++i)
    73     {
    74         for (int j = 0; j < N; ++j)
    75         {
    76             scanf("%d", &cost[i][j]);
    77         }
    78     }
    79     Solve();
    80 
    81 #ifdef HOME
    82     cerr << "Time elapsed: " << clock() / CLOCKS_PER_SEC << " ms" << endl;
    83     _CrtDumpMemoryLeaks();
    84 #endif
    85     return 0;
    86 }
    
    
    
     
  • 相关阅读:
    Android-Java-构造方法内存图
    redis conf 详解
    redis windows 下安装及使用
    Python 学习笔记(一)
    python 配置
    win 7 下vim的使用
    window下安装Node.js NPM
    HashMap实现原理(转)
    mysql 常用功能
    MySql配置
  • 原文地址:https://www.cnblogs.com/shijianming/p/5052360.html
Copyright © 2020-2023  润新知