示例#1
0
 public LazyPrimMST(IEdgeWeightGraph g)
 {
     pq     = new MinPQ <IEdge>();
     marked = new bool[g.V];
     mst    = new Chapter1.Queue <IEdge>();
     Visit(g, 0);//假设G是联通的
     while (!pq.IsEmpty)
     {
         IEdge e = pq.Delete(); //找到权重最小的边
         int   v = e.Either;
         int   w = e.Other(v);
         if (marked[v] && marked[w]) //跳过失效的边
         {
             continue;
         }
         mst.Enqueue(e); //将边添加到树中
         if (!marked[v])
         {
             Visit(g, v);
         }
         if (!marked[w])
         {
             Visit(g, w);
         }
     }
 }
        private Node BuildTrie(int[] freq)
        {
            MinPQ <Node> pq = new MinPQ <Node>();

            for (char c = (char)0; c < (char)R; c++)
            {
                if (freq[c] > 0)
                {
                    pq.Insert(new Node(c, freq[c], null, null));
                }
            }
            while (pq.Size > 1)
            {
                Node x      = pq.Delete();
                Node y      = pq.Delete();
                Node parent = new Node('\0', x.freq + y.freq, x, y);
                pq.Insert(parent);
            }
            return(pq.Delete());
        }
        public KruskalMST(IEdgeWeightGraph G)
        {
            mst = new Chapter1.Queue <IEdge>();
            MinPQ <IEdge> pq = new MinPQ <IEdge>();

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

            while (!pq.IsEmpty && mst.Size < G.V - 1)
            {
                IEdge e = pq.Delete();  //找到权重最小的边
                int   v = e.Either, w = e.Other(v);
                if (uf.Connected(v, w)) //忽略失效的边
                {
                    continue;
                }
                uf.Union(v, w);
                mst.Enqueue(e);
            }
        }