zoukankan      html  css  js  c++  java
  • POJ.1287 Networking (Prim)

    POJ.1287 Networking (Prim)

    题意分析

    1. 可能有重边,注意选择最小的边。
    2. 编号依旧从1开始。
    3. 直接跑prim即可。

    代码总览

    #include <cstdio>
    #include <cstring>
    #define nmax 105
    #define inf 1e8+7
    using namespace std;
    int mp[nmax][nmax];
    bool isfind  = true;
    int n,m;
    int totaldis =0;
    void prim()
    {
        int lowcost[nmax];
        int path[nmax];
        for(int j = 1;j<=n;++j){
            lowcost[j] = mp[1][j];
            path[j] = 1;
        }
        path[1] = 0;
        int nowmin,nowminid;
        for(int i =2 ;i<=n;++i){
            nowmin = inf;
            nowminid = 0;
            for(int j = 2;j<=n;++j){
                if(nowmin > lowcost[j] && lowcost[j] != 0){
                    nowmin = lowcost[j];
                    nowminid = j;
                }
            }
            if(nowmin == inf){
                isfind = false;
                return;
            }
            totaldis += nowmin;
            lowcost[nowminid] = 0;
            for(int j = 2;j<=n;++j){
                if(mp[nowminid][j] < lowcost[j]){
                    lowcost[j] = mp[nowminid][j];
                    path[j] = nowminid;
                }
            }
        }
    }
    int main()
    {
        //freopen("in.txt","r",stdin);
        while(scanf("%d",&n) != EOF && n){
            scanf("%d",&m);
            int sta,end,dis;
            totaldis = 0;
            isfind =  true;
            for(int i = 1; i<=n;++i)
                for(int j = 1;j<=n;++j)
                    mp[i][j] = inf;
            for(int i = 1; i<=m ;++i){
                scanf("%d %d %d",&sta,&end,&dis);
                if(mp[sta][end] != inf){
                    int temp = mp[sta][end];
                    if(dis < temp)
                        mp[sta][end] = mp[end][sta] = dis;
                }else{
                    mp[sta][end] = mp[end][sta] = dis;
                }
            }
            prim();
            if(isfind == false) totaldis = 0;
            printf("%d
    ",totaldis);
        }
        return 0;
    }
    
  • 相关阅读:
    Python模块之pysnooper
    本站页脚HTML回顶部代码
    本站CSS代码
    Linux使用 tar命令-g参数进行增量+差异备份、还原文件
    mysql定时备份shell脚本
    Linux系统备份与还原
    MYSQL备份与恢复
    技术普及帖:你刚才在淘宝上买了一件东西
    Linux运维工程师前景
    Linux运维工程师需掌握的技能
  • 原文地址:https://www.cnblogs.com/pengwill/p/7367069.html
Copyright © 2011-2022 走看看