Ejemplo n.º 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);
         }
     }
 }
Ejemplo n.º 2
0
        private IEnumerable <IDirectedEdge> cycle; //edgeTo中是否含有负权重环

        public BellmanFordSP(IEdgeWeightedDIgraph G, int s) : base(G, s)
        {
            onQ   = new bool[G.V];
            queue = new Chapter1.Queue <int>();
            queue.Enqueue(s);
            onQ[s] = true;
            while (!queue.IsEmpty && !HasNegativeCycle())
            {
                int v = queue.Dequeue();
                onQ[v] = false;
                Relax(G, v);
            }
        }
Ejemplo n.º 3
0
        public IEnumerable <IEdge> Edges()
        {
            var mst = new Chapter1.Queue <IEdge>();

            for (int v = 0; v < edgeTo.Length; v++)
            {
                IEdge e = edgeTo[v];
                if (e != null)
                {
                    mst.Enqueue(e);
                }
            }
            return(mst);
        }
        private void Bfs(IGraph g, int s)
        {
            var queue = new Chapter1.Queue <int>();

            marked[s] = true; //起点被标记
            queue.Enqueue(s);
            while (!queue.IsEmpty)
            {
                int v = queue.Dequeue(); //从队列中删除一个顶点
                foreach (int w in g.Adj(v))
                {
                    if (!marked[w])
                    {
                        edgeTo[w] = v;
                        marked[w] = true;
                        queue.Enqueue(w);
                    }
                }
            }
        }
Ejemplo n.º 5
0
        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);
            }
        }