private Queue <Edge> mst = new Queue <Edge>(); // edges in MST

        /**
         * Compute a minimum spanning tree (or forest) of an edge-weighted graph.
         * @param G the edge-weighted graph
         */
        public KruskalMST(EdgeWeightedGraph G)
        {
            // more efficient to build heap by passing array of edges
            MinPQ <Edge> pq = new MinPQ <Edge>();

            foreach (Edge e in G.Edges)
            {
                pq.Insert(e);
            }

            // run greedy algorithm
            UF uf = new UF(G.V);

            while (!pq.IsEmpty && mst.Size < G.V - 1)
            {
                Edge e = pq.DeleteMin();
                int  v = e.Either;
                int  w = e.other(v);
                if (!uf.Connected(v, w))
                { // v-w does not create a cycle
                  // merge v and w components
                    uf.Union(v, w);
                    mst.Enqueue(e); // add edge e to mst
                    weight += e.Weight;
                }
            }

            // check optimality conditions
            //assert ;
            Contract.Assert(check(G));
        }
        public override ArrayPQBase <TKey> Clone()
        {
            // return new MinPQ<TKey>(this.pq, this.comparator);
            var clone = new MinPQ <TKey>(this.pq.Length);

            clone.n          = this.n;
            clone.pq         = this.pq;
            clone.comparator = this.comparator;
            return(clone);
        }
Esempio n. 3
0
        private MinPQ <Edge> pq;  // edges with one endpoint in tree

        /**
         * Compute a minimum spanning tree (or forest) of an edge-weighted graph.
         * @param G the edge-weighted graph
         */
        public LazyPrimMST(EdgeWeightedGraph G)
        {
            mst    = new Queue <Edge>();
            pq     = new MinPQ <Edge>();
            marked = new bool[G.V];
            for (int v = 0; v < G.V; v++) // run Prim from all vertices to
            {
                if (!marked[v])
                {
                    prim(G, v);         // get a minimum spanning forest
                }
            }
            // check optimality conditions
            //Contracts.Assert (G);
        }