예제 #1
0
 private void visit(EdgeWeightedGraph G, int v)
 {
     // Mark v and add to pq all edges from v to unmarked vertices.
     marked[v] = true;
     foreach (Edge e in G.Adj(v))
         if (!marked[e.other(v)])
             pq.Insert(e);
 }
예제 #2
0
        private IndexPriorityQueue<Double> pq; // eligible crossing edges

        #endregion Fields

        #region Constructors

        public PrimMST(EdgeWeightedGraph G)
        {
            edgeTo = new Edge[G.V];
            distTo = new double[G.V];
            marked = new bool[G.V];
            for (int v = 0; v < G.V; v++)
                distTo[v] = Double.PositiveInfinity;
            pq = new IndexPriorityQueue<double>(G.V);
            distTo[0] = 0.0;
            pq.Insert(0, 0.0); // Initialize pq with 0, weight 0.
            while (!pq.isEmpty())
                visit(G, pq.Del()); // Add closest vertex to tree.
        }
예제 #3
0
        static void Main(string[] args)
        {
            EdgeWeightedGraph ewg=new EdgeWeightedGraph(5);

            ewg.Filling(5);
            ewg.ShowEdges();
            Console.WriteLine();

            ewg.LazyPrimAlgr();
            Console.WriteLine();

            ewg.PrimAlgr();

            Console.ReadKey();
        }
예제 #4
0
 private void visit(EdgeWeightedGraph G, int v)
 {
     // Add v to tree; update data structures.
     marked[v] = true;
     foreach (Edge e in G.Adj(v))
     {
         int w = e.other(v);
         if (marked[w]) continue; // v-w is ineligible.
         if (e.Weight < distTo[w])
         { // Edge e is new best connection from tree to w.
             edgeTo[w] = e;
             distTo[w] = e.Weight;
             if (pq.contains(w)) pq.change(w, distTo[w]);
             else pq.Insert(w, distTo[w]);
         }
     }
 }
예제 #5
0
        private PriorityQueue<Edge> pq; // crossing (and ineligible) edges

        #endregion Fields

        #region Constructors

        public LazyPrimMST(EdgeWeightedGraph G)
        {
            pq = new PriorityQueue<Edge>(G.V);
            marked = new bool[G.V];
            mst = new Queue<Edge>();
            visit(G, 0); // assumes G is connected (see Exercise 4.3.22)
            while (!pq.isEmpty())
            {
                Edge e = pq.Del(); // Get lowest-weight
                int v = e.either;
                int w = e.other(v); // edge from pq.
                if (marked[v] && marked[w])
                    continue; // Skip if ineligible.
                mst.Enqueue(e); // Add edge to tree.
                if (!marked[v])
                    visit(G, v); // Add vertex to tree
                if (!marked[w])
                    visit(G, w); // (either v or w).
            }
        }