zoukankan      html  css  js  c++  java
  • 最小生成树Prim——最短网络(洛谷1546)(USACO 3.1.1)可当Prim模板

     题目背景 Background
    农民约翰被选为他们镇的镇长!他其中一个竞选承诺就是在镇上建立起互联网,并连接到所有的农场。当然,他需要你的帮助。
     题目描述 Description
    约翰已经给他的农场安排了一条高速的网络线路,他想把这条线路共享给其他农场。为了用最小的消费,他想铺设最短的光纤去连接所有的农场。
    你将得到一份各农场之间连接费用的列表,你必须找出能连接所有农场并所用光纤最短的方案。每两个农场间的距离不会超过100000
     输入输出格式 Input/output
    输入格式:
    第一行: 农场的个数,N(3<=N<=100)。
    第二行..结尾: 后来的行包含了一个N*N的矩阵,表示每个农场之间的距离。理论上,他们是N行,每行由N个用空格分隔的数组成,实际上,他们限制在80个字符,因此,某些行会紧接着另一些行。当然,对角线将会是0,因为不会有线路从第i个农场到它本身。
    输出格式:
    只有一个输出,其中包含连接到每个农场的光纤的最小长度。
     输入输出样例 Sample input/output
    样例测试点#1
    输入样例: 

    4
    0 4 9 21
    4 0 8 17
    9 8 0 16
    21 17 16 0


    输出样例:
    28
     
    代码:

    var n,m,i,j,k,s,t,p,min:longint;

        dis:array[0..100] of longint;

        f:array[0..100] of boolean;

        map:array[0..100,0..100] of longint;

    procedure prim;

    var i,j:longint;

    begin

      fillchar(f,sizeof(f),true);

      f[1]:=false;

      for i:=1 to n do dis[i]:=map[1,i];//记录第一个点的到其它点距离

      for i:=1 to n-1 do

        begin

           //找出当前点到其它点的最小值,并记录新的点P

          min:=maxlongint;

          for j:=1 to n do

            if f[j] and (min>dis[j]) then

              begin

                min:=dis[j];

                p:=j;

              end;

          f[p]:=true;//新的最小值的点不再参与比较

          s:=s+dis[p];//记录最短值

          for j:=1 to n do  //新点到其它点的距离与原距离比较并更新小的

            if f[j] and (dis[j]>map[p,j]) then

              dis[j]:=map[p,j];

        end;

    end;

    begin

      readln(n);

      for i:=1 to n do

        begin

          for j:=1 to n do read(map[i,j]);

          readln;

        end;

       prim;

      writeln(s);

    end.

  • 相关阅读:
    面试范围
    Spark集群基础概念 与 spark架构原理
    RDD 算子补充
    常用Actoin算子 与 内存管理 、共享变量、内存机制
    常用Transformation算子
    spark core (二)
    Spark 介绍
    JSON对象和string的相互转换
    javascript中substring和substr方法
    mongodb学习相关网址
  • 原文地址:https://www.cnblogs.com/zqzxwdm/p/4743766.html
Copyright © 2011-2022 走看看