Пример #1
0
 private void visit(EdgeWightedGraph g, Int32 v)
 {
     marked[v] = true;
     foreach (Edge e in g.Adj(v))
     {
         int w = e.Other(v);
         if (marked[w])
         {
             continue;//访问过了
         }
         if (e.Weight < disTo[w])
         {
             //从MST到w的距离变短了。最佳边变成e
             edgeTo[w] = e;
             disTo[w]  = e.Weight;
             if (pq.Contains(w))
             {
                 pq.Change(w, disTo[w]);
             }
             else
             {
                 pq.Insert(w, disTo[w]);
             }
         }
     }
 }
 private Chapter2.SortDemos.IndexPriorityQueue <Double> pq; //始终有最短的边
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="graph">有向加权非负权图</param>
 /// <param name="s">起点</param>
 public DijkstraSP(DirectedWeightedGraph graph, int s)
 {
     edgeTo = new DirectedEdge[graph.V];
     disTo  = new Double[graph.V];
     pq     = new Chapter2.SortDemos.IndexPriorityQueue <double>(graph.V);
     for (Int32 v = 0; v < graph.V; ++v)
     {
         disTo[v] = Double.PositiveInfinity;
     }
     disTo[s] = 0.0;//自己到自己为0
     pq.Insert(s, 0.0);
     while (!pq.IsEmpty())
     {
         Relax(graph, pq.DeleteMin());//放松节点,找到到某个点的最短的距离
     }
 }
Пример #3
0
 private Chapter2.SortDemos.IndexPriorityQueue <Double> pq; //保存最小边的最小堆
 public PrimMST(EdgeWightedGraph g)
 {
     pq = new Chapter2.SortDemos.IndexPriorityQueue <double>(g.V, (Double s, Double b) =>
     {
         return(s < b);
     });//允许的标号[0,g.V]
     edgeTo = new Edge[g.V];
     marked = new Boolean[g.V];
     disTo  = new Double[g.V];
     for (Int32 v = 0; v < g.V; ++v)
     {
         disTo[v] = Double.PositiveInfinity; //表示为正无穷
     }
     pq.Insert(0, 0.0);
     disTo[0] = 0.0;
     while (!pq.IsEmpty())
     {
         visit(g, pq.DeleteMin());//获取二叉堆中总是最小的索引
     }
 }
 private void Relax(DirectedWeightedGraph g, int v)
 {
     foreach (DirectedEdge edge in g.GetEdge(v))
     {
         int w = edge.End;
         //如果存在放松的条件
         if (disTo[w] > disTo[v] + edge.Weight)
         {
             //存在,需要更新
             disTo[w]  = disTo[v] + edge.Weight;
             edgeTo[w] = edge;
             //重新累计从 s 到某个点的最短距离。这个距离只有可能减小
             if (pq.Contains(w))
             {
                 pq.Change(w, disTo[w]);
             }
             else
             {
                 pq.Insert(w, disTo[w]);
             }
         }
     }
 }