• Prim算法


    解决这个问题我用的是Set集合,因为Set有不加重复元素,又可以迭代其中的元素,以及知道其大小等优点。

    我们把树上的所有顶点分成2部分,已经访问的顶点称之为U,还没访问的称之为  V-U,找最小生成树的过程就是 遍历V-U中的点,使他们到U中的某个点距离最小!!

    然后再把这个点加入到U中

    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.Scanner;
    /*
     *设G=(V,E)是无相连通带权图,找出最小生成树,也就是找出权值和最小的生成树。
     *
     测试用例:
    10 6
    1 2 6 1 3 1 1 4 5
    2 5 3 2 3 5
    3 5 6 3 6 4
    3 4 5
    4 6 2
    5 6 6
     */
    import java.util.Set;
    
    public class Test {
        static int edge,node;   //边数、顶点数
        static int [][] c=new int[20][20];
        static boolean  []s=new boolean[20];  //如果s[i]=true,说明该顶点已经属于最小生成树的一部分
        static Scanner sc=new Scanner(System.in);
        static Set<Integer> set=new HashSet<Integer>();   //set表示U集合
        public static void main(String[] args) {
            int edge,node,f,t,v;
            edge=sc.nextInt();
            node=sc.nextInt();
            set.clear();
            for(int i=1;i<=node;i++){
                for(int j=1;j<=node;j++){
                    c[i][j]=10000;
                    c[j][i]=10000;
                }
                
            }
            for(int i=1;i<=edge;i++){
                f=sc.nextInt();
                t=sc.nextInt();
                v=sc.nextInt();
                c[f][t]=v;
                c[t][f]=v;
            }
            set.add(1);
            prim(node, 1);
            
        }
        
        public static void prim(int n,int u){
            s[u]=true;
            int u0,mini=1000,k=0;
            while(set.size()<n){
                Iterator<Integer> iterator = set.iterator();
                mini=1000;
                while(iterator.hasNext()){
                 u0= (int)iterator.next();
                    for(int i=1;i<=n;i++){
                        if(i!=u0&&c[i][u0]<mini&&s[i]==false){
                            mini=c[i][u0];
                            k=i;
                        }
                    }
                }
                set.add(k);
                s[k]=true;
                System.out.println(k);
            }
        }
    }
  • 相关阅读:
    700. Search in a Binary Search Tree
    100. Same Tree
    543. Diameter of Binary Tree
    257. Binary Tree Paths
    572. Subtree of Another Tree
    226. Invert Binary Tree
    104. Maximum Depth of Binary Tree
    1、解决sublime打开文档,出现中文乱码问题
    移植seetafaceengine-master、opencv到ARM板
    ubuntu16.04-交叉编译-SeetaFaceEngine-master
  • 原文地址:https://www.cnblogs.com/wintersong/p/5034357.html
Copyright © 2020-2023  润新知