Esempio n. 1
0
 private MinPQ <Edge> pq;    //横切边(包括失效的边)
 public LazyPrimMST(EdgeWeightedGraph G)
 {
     pq     = new MinPQ <Edge>();
     marked = new bool[G.VNumber];
     mst    = new Queue <Edge>();
     Visit(G, 0);
     while (!pq.IsEmpty())
     {
         Edge e = pq.DelMin();                //从pq中得到权重最小的边
         int  v = e.Either;
         int  w = e.Other(v);
         if (marked[v] && marked[w])
         {
             continue;                        //跳过失效的边
         }
         mst.enqueue(e);                      //将边添加到树中
         if (!marked[v])
         {
             Visit(G, v);                     //将顶点(v或w)添加到树中
         }
         if (!marked[w])
         {
             Visit(G, w);
         }
     }
 }
Esempio n. 2
0
        public KruskalMST(EdgeWeightedGraph G)
        {
            mst = new Queue <Edge>();
            MinPQ <Edge> pq = new MinPQ <Edge>();

            foreach (Edge e in G.Edges())
            {
                pq.Insert(e);
            }
            UF uf = new UF(G.VNumber);

            while (!pq.IsEmpty() && mst.Size() < G.VNumber - 1)
            {
                Edge e = pq.DelMin();  //从pq得到权重最小的边和它的顶点
                int  v = e.Either, w = e.Other(v);
                if (uf.Connected(v, w))
                {
                    continue;
                }
                uf.Union(v, w);   //合并分量
                mst.enqueue(e);   //将边添加到最小生成树中
            }
        }