zoukankan      html  css  js  c++  java
  • POJ-2421 Constructing Roads---确定部分边的MST

    题目链接:

    https://vjudge.net/problem/POJ-2421

    题目大意:

    还是给你n个点,然后求最小生成树。特殊之处在于有一些点之间已经连上了边。

    思路:

    POJ-1751一样的,将已有的边的权值设置成0即可

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<cstring>
     4 #include<algorithm>
     5 #include<cmath>
     6 #include<queue>
     7 #include<stack>
     8 #include<map>
     9 #include<sstream>
    10 using namespace std;
    11 typedef long long ll;
    12 const int maxn = 2e2 + 10;
    13 const int INF = 1 << 30;
    14 int dir[4][2] = {1,0,0,1,-1,0,0,-1};
    15 int T, n, m, x;
    16 int Map[maxn][maxn];//存图
    17 int lowcost[maxn], mst[maxn];
    18 void prim(int u)//最小生成树起点
    19 {
    20     int sum_mst = 0;//最小生成树权值
    21     for(int i = 1; i <= n; i++)//初始化两个数组
    22     {
    23         lowcost[i] = Map[u][i];
    24         mst[i] = u;
    25     }
    26     mst[u] = -1;//设置成-1表示已经加入mst
    27     for(int i = 1; i <= n; i++)
    28     {
    29         int minn = INF;
    30         int v = -1;
    31         //在lowcost数组中寻找未加入mst的最小值
    32         for(int j = 1; j <= n; j++)
    33         {
    34             if(mst[j] != -1 && lowcost[j] < minn)
    35             {
    36                 v = j;
    37                 minn = lowcost[j];
    38             }
    39         }
    40         if(v != -1)//v=-1表示未找到最小的边,
    41         {//v表示当前距离mst最短的点
    42             //printf("%d %d %d
    ", mst[v], v, lowcost[v]);//输出路径
    43             mst[v] = -1;
    44             sum_mst += lowcost[v];
    45             for(int j = 1; j <= n; j++)//更新最短边
    46             {
    47                 if(mst[j] != -1 && lowcost[j] > Map[v][j])
    48                 {
    49                     lowcost[j] = Map[v][j];
    50                     mst[j] = v;
    51                 }
    52             }
    53         }
    54     }
    55     //printf("weight of mst is %d
    ", sum_mst);
    56     cout<<sum_mst<<endl;
    57 }
    58 int main()
    59 {
    60     cin >> n;
    61     for(int i = 1; i <= n; i++)
    62     {
    63         for(int j = 1; j <= n; j++)cin >> Map[i][j];
    64     }
    65     int x, y;
    66     cin >> m;
    67     while(m--)
    68     {
    69         cin >> x >> y;
    70         Map[x][y] = Map[y][x] = 0;
    71     }
    72     prim(1);
    73     return 0;
    74 }
  • 相关阅读:
    京东精益敏捷教练分享:敏捷助力产品创新!
    设计规范 | 详解组件控件结构体系
    Axure响应式进阶
    通讯录表设计
    TEST1
    c#练习四单元总结
    窗体控件应用总结(1)
    .NET(c#理解)
    test2-11
    test1-1
  • 原文地址:https://www.cnblogs.com/fzl194/p/8727438.html
Copyright © 2011-2022 走看看