예제 #1
0
    private IndexMinPQ<Double> pq;    // priority queue of vertices

    /**
     * Computes a shortest-paths tree from the source vertex {@code s} to every
     * other vertex in the edge-weighted graph {@code G}.
     *
     * @param  G the edge-weighted digraph
     * @param  s the source vertex
     * @throws IllegalArgumentException if an edge weight is negative
     * @throws IllegalArgumentException unless {@code 0 <= s < V}
     */
    public DijkstraUndirectedSP(EdgeWeightedGraph G, int s) {
        for (Edge e : G.edges()) {
            if (e.weight() < 0)
                throw new IllegalArgumentException("edge " + e + " has negative weight");
        }

        distTo = new double[G.V()];
        edgeTo = new Edge[G.V()];

        validateVertex(s);

        for (int v = 0; v < G.V(); v++)
            distTo[v] = Double.POSITIVE_INFINITY;
        distTo[s] = 0.0;

        // relax vertices in order of distance from s
        pq = new IndexMinPQ<Double>(G.V());
        pq.insert(s, distTo[s]);
        while (!pq.isEmpty()) {
            int v = pq.delMin();
            for (Edge e : G.adj(v))
                relax(e, v);
        }

        // check optimality conditions
        assert check(G, s);
    }
예제 #2
0
    private static void merge(int[] streams)
    {
        int n = streams.Length;

        IndexMinPQ <string> pq = new IndexMinPQ <string>(n);

        for (int i = 0; i < n; i++)
        {
            if (!streams[i].Equals(null))
            {
                pq.insert(i, streams[i].ToString());
            }
        }

        // Extract and print min and read next from its stream.
        while (!pq.isEmpty())
        {
            print(pq.minKey() + " ");
            int i = pq.delMin();
            if (!streams[i].Equals(null))
            {
                pq.insert(i, streams[i].ToString());
            }
        }
    }
예제 #3
0
        public Dijkstra(WeightedDiGraph G, int s)
        {
            this.s = s;
            int V = G.V();

            marked = new bool[V];
            edgeTo = new Edge[V];
            cost   = new double[V];

            for (var i = 0; i < V; ++i)
            {
                cost[i] = Double.MaxValue;
            }

            cost[s] = 0;

            pq = new IndexMinPQ <Double>(V);


            pq.Insert(s, 0);

            while (!pq.IsEmpty)
            {
                var v = pq.DelMin();
                marked[v] = true;
                foreach (var e in G.adj(v))
                {
                    Relax(G, e);
                }
            }
        }
        public DijkstraSP(EdgeWeightedDigraph g, int s)
        {
            foreach (DirectedEdge e in g.Edges())
            {
                if (e.Weight() < 0)
                {
                    throw new ArgumentOutOfRangeException("graph edge must have nonegative weights");
                }
            }

            distTo = new double[g.V];
            edgeTo = new DirectedEdge[g.V];
            for (int v = 0; v < g.V; v++)
            {
                distTo[v] = double.PositiveInfinity;
            }
            distTo[s] = 0;

            //relax vertices in order of distance from s
            pq = new IndexMinPQ <double>(g.V);
            pq.Insert(s, distTo[s]);
            while (!pq.IsEmpty())
            {
                int v = pq.DelMin();
                foreach (DirectedEdge e in g.Adj(v))
                {
                    relax(e);
                }
            }
        }
예제 #5
0
        /// <summary>
        /// Dijkstra algorithm (shortest path) based on graph g for start vertice s. Positive cycles are allowed in shortest path algorithm
        /// </summary>
        /// <param name="g">Graph for search</param>
        /// <param name="s">Start vertice</param>
        public static PathStats ShortestPath(GraphBase g, int s)
        {
            var ps = new PathStats(g.V);

            for (var i = 0; i < ps.Dist.Length; i++)
            {
                ps.Dist[i] = int.MaxValue;
                ps.Prev[i] = -1;
            }

            ps.Dist[s] = 0;//start vertice

            var pq = new IndexMinPQ<Distance>(ps.Dist.Length);
            for (int i = 0; i < ps.Dist.Length; i++)
            {
                pq.Insert(i, new Distance { V = i, Dist = ps.Dist[i] });
            }

            while (!pq.IsEmpty())
            {
                var v = pq.DelRoot();

                foreach (var e in g.Adjacent(v))
                {
                    if (ps.Dist[e.V2] > ps.Dist[v] + e.Weight)
                    {
                        ps.Dist[e.V2] = ps.Dist[v] + e.Weight;
                        ps.Prev[e.V2] = v;
                        pq.ChangeKey(e.V2, new Distance { V = e.V2, Dist = ps.Dist[e.V2] });
                    }
                }
            }

            return ps;
        }
        public void IndexMinPQIteratorTest()
        {
            var pq     = new IndexMinPQ <String>(array);
            var actual = Strings(pq).ToList();

            Assert.Equal(indexedMin, actual);
        }
예제 #7
0
        private readonly IndexMinPQ <Double> _pq;   // priority queue of vertices

        /// <summary>
        /// Computes a shortest-paths tree from the source vertex <tt>s</tt> to every other
        /// vertex in the edge-weighted digraph <tt>G</tt>.
        /// </summary>
        /// <param name="g">g the edge-weighted digraph</param>
        /// <param name="s">s the source vertex</param>
        /// <exception cref="ArgumentException">if an edge weight is negative</exception>
        /// <exception cref="ArgumentException">unless 0 &lt;= <tt>s</tt> &lt;= <tt>V</tt> - 1</exception>
        public DijkstraSP(EdgeWeightedDigraph g, int s)
        {
            foreach (var e in g.Edges())
            {
                if (e.Weight < 0)
                {
                    throw new ArgumentException($"edge {e} has negative weight");
                }
            }

            _distTo = new double[g.V];
            _edgeTo = new DirectedEdge[g.V];
            for (var v = 0; v < g.V; v++)
            {
                _distTo[v] = double.PositiveInfinity;
            }
            _distTo[s] = 0.0;

            // relax vertices in order of distance from s
            _pq = new IndexMinPQ <Double>(g.V);
            _pq.Insert(s, _distTo[s]);
            while (!_pq.IsEmpty())
            {
                var v = _pq.DelMin();
                foreach (var e in g.Adj(v))
                {
                    Relax(e);
                }
            }

            // check optimality conditions
            //assert check(G, s);
        }
예제 #8
0
        public void Test()
        {
            var pq = new IndexMinPQ <int>(10);

            pq.Enqueue(1, 20);
            pq.Enqueue(2, 15);

            Assert.Equal(15, pq.MinKey());

            pq.Enqueue(1, 10);

            Assert.Equal(10, pq.MinKey());

            pq.Enqueue(3, 11);

            Assert.Equal(1, pq.DelMin());

            Assert.Equal(11, pq.MinKey());

            Assert.Equal(2, pq.Count);

            Assert.False(pq.IsEmpty);

            pq.Enqueue(2, 10);

            Assert.Equal(10, pq.MinKey());
            Assert.Equal(2, pq.DelMin());

            foreach (var v in pq)
            {
                console.WriteLine("key: {0}", v);
            }
        }
 public void EnumeratorMinPQTest()
 {
     // Expected: same as sorting the input and inserting it in a regular queue
      Queue<string> expectedItems = new Queue<string>(this.testStrings.OrderBy(s => s));
      IndexMinPQ<string> pq = new IndexMinPQ<string>(this.testStrings.Length);
      CommonIndexPQUnitTests.EnumerationPQTest(this.testStrings, pq, expectedItems);
 }
        public LazyPrimMinSpanningTree(EdgeWeightedGraph g)
        {
            pq     = new IndexMinPQ <Edge>(g.EdgeCount);
            marked = new bool[g.VertexCount];
            mst    = new Queue <Edge>();

            Visit(g, 0);
            while (!pq.IsEmpty())
            {
                Edge e  = pq.DelMin();
                int  v1 = e.CurrentValue;
                int  v2 = e.Other(v1);
                if (marked[v1] && marked[v2])
                {
                    continue;
                }

                mst.Enqueue(e);
                if (marked[v1])
                {
                    Visit(g, v1);
                }

                if (!marked[v2])
                {
                    Visit(g, v2);
                }
            }
        }
예제 #11
0
 public void Initialize()
 {
     _target = new IndexMinPQ<Distance>(4);
     _target.Insert(2, new Distance { V = 2, Dist = 1 });
     _target.Insert(1, new Distance { V = 1, Dist = 2 });
     _target.Insert(0, new Distance { V = 0, Dist = 3 });
 }
예제 #12
0
        private readonly IndexMinPQ<Double> _pq; // priority queue of vertices

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Computes a shortest-paths tree from the source vertex <tt>s</tt> to every
        /// other vertex in the edge-weighted graph <tt>G</tt>.
        /// </summary>
        /// <param name="g">g the edge-weighted graph</param>
        /// <param name="s">s the source vertex</param>
        /// <exception cref="ArgumentException">if an edge weight is negative</exception>
        /// <exception cref="ArgumentException">unless 0 &lt;= <tt>s</tt> &lt;= <tt>V</tt> - 1</exception>
        public DijkstraUndirectedSP(EdgeWeightedGraph g, int s)
        {
            foreach (var e in g.Edges())
            {
                if (e.Weight < 0)
                    throw new ArgumentException($"edge {e} has negative weight");
            }

            _distTo = new double[g.V];
            _edgeTo = new EdgeW[g.V];
            for (var v = 0; v < g.V; v++)
                _distTo[v] = double.PositiveInfinity;
            _distTo[s] = 0.0;

            // relax vertices in order of distance from s
            _pq = new IndexMinPQ<Double>(g.V);
            _pq.Insert(s, _distTo[s]);
            while (!_pq.IsEmpty())
            {
                var v = _pq.DelMin();
                foreach (var e in g.Adj(v))
                    Relax(e, v);
            }

            // check optimality conditions
            //assert check(G, s);
        }
예제 #13
0
 public void Merge3WayMinPQTest()
 {
     string[] inputFiles = { "Algs4-Data\\m1.txt", "Algs4-Data\\m2.txt", "Algs4-Data\\m3.txt" };
      Queue<string> expectedItems = new Queue<string>(
     "A B C F G I I Z B D H P Q Q A B E F J N".Split(" ".ToCharArray()).OrderBy(s => s));
      IndexMinPQ<string> pq = new IndexMinPQ<string>(expectedItems.Count);
      CommonIndexPQUnitTests.MergeMultiWay(inputFiles, pq, expectedItems);
 }
예제 #14
0
파일: MinPQ.cs 프로젝트: rrliu/fireline
 // add all items to copy of heap
 // takes linear time since already in heap order so no keys move
 public HeapIEnumerator(IndexMinPQ <Key> minpq)
 {
     innerPQ = new IndexMinPQ <Key>(minpq.Count);
     for (int i = 1; i <= minpq.N; i++)
     {
         innerPQ.Insert(minpq.pq[i], minpq.keys[minpq.pq[i]]);
     }
     copy = innerPQ;
 }
예제 #15
0
 public DijkstraSP(IEdgeWeightedDIgraph G, int s) : base(G, s)
 {
     pq = new IndexMinPQ <double>(G.V);
     pq.Insert(s, 0.0);
     while (!pq.IsEmpty)
     {
         Relax(G, pq.DeleteMin());
     }
 }
예제 #16
0
        public Multiway(List<List<string>> lists)
        {
            var n = lists.Sum(l => l.Count);
            _n = n;
            _pq = new IndexMinPQ<string>(n);

            foreach (var list in lists)
            {
               InsertWords(list);

            }
        }
예제 #17
0
파일: PrimMST.cs 프로젝트: qizl/Algorithms
        public PrimMST(EdgeWeightedGraph g)
        {
            this._edgeTo = new Edge[g.V()];
            this._distTo = new double[g.V()];
            this._marked = new bool[g.V()];
            this._pq = new IndexMinPQ<double>(g.V());
            for (int v = 0; v < g.V(); v++)
                this._distTo[v] = double.PositiveInfinity;

            for (int v = 0; v < g.V(); v++)
                if (!this._marked[v])
                    this.prim(g, v);
        }
예제 #18
0
        public DifkstraSP(EdgeWeightedDigraph g, int s)
        {
            _edgeTo    = new DirectedEdge[g.V];
            _distTo    = Enumerable.Repeat(double.PositiveInfinity, g.V).ToArray();
            _pq        = new IndexMinPQ <double>(g.V);
            _distTo[s] = 0.0;

            _pq.Insert(s, 0.0);
            while (!_pq.IsEmpty())
            {
                Relax(g, _pq.DelMin());
            }
        }
예제 #19
0
    public void IndexMinPQ_Enqueue()
    {
        var q = new IndexMinPQ<int>(items.Length);
        var minItem = int.MaxValue;

        for (int i = 0; i < items.Length; i++)
        {
            // After adding each item, the min item should be on top
            q.Insert(i, items[i]);
            minItem = Math.Min(items[i], minItem);

            Assert.AreEqual(q.MinKey(), minItem);
        }
    }
예제 #20
0
    /**
     * Compute a minimum spanning tree (or forest) of an edge-weighted graph.
     * @param G the edge-weighted graph
     */
    public PrimMST(EdgeWeightedGraph G) {
        edgeTo = new Edge[G.V()];
        distTo = new double[G.V()];
        marked = new boolean[G.V()];
        pq = new IndexMinPQ<Double>(G.V());
        for (int v = 0; v < G.V(); v++)
            distTo[v] = Double.POSITIVE_INFINITY;

        for (int v = 0; v < G.V(); v++)      // run from each vertex to find
            if (!marked[v]) prim(G, v);      // minimum spanning forest

        // check optimality conditions
        assert check(G);
    }
        public void IndexedMinPQDecreaseKeyTest()
        {
            // arrange
            var pq = new IndexMinPQ <string>(array);

            // act + assert initial
            Assert.False(pq.IsEmpty);
            Assert.Equal(10, pq.Size);
            Assert.Equal(3, pq.Index);
            Assert.Equal(3, pq.MinIndex);
            Assert.Equal("best", pq.Min);
            Assert.Equal("best", pq.TopKey);

            // act + assert ex
            try
            {
                pq.decreaseKey(int.MaxValue - 1, null);
            }
            catch (Exception ex)
            {
                Assert.IsType <ArgumentOutOfRangeException>(ex);
            }

            try
            {
                pq.decreaseKey(10, null);
            }
            catch (Exception ex)
            {
                Assert.IsType <ArgumentOutOfRangeException>(ex);
            }

            // act + assert decrease
            try
            {
                pq.decreaseKey(5, "zzz");
            }
            catch (Exception ex)
            {
                Assert.IsType <ArgumentException>(ex);
                Assert.Equal("Calling decreaseKey() with given argument would not strictly decrease the key", ex.Message);
            }

            pq.decreaseKey(5, "aaa");
            Assert.Equal("aaa", pq.Min);
            Assert.Equal("aaa", pq.TopKey);
            Assert.Equal(5, pq.Index);
            Assert.Equal(5, pq.MinIndex);
        }
예제 #22
0
파일: MinPQ.cs 프로젝트: rrliu/fireline
    /// <summary>
    /// Demo test the <c>IndexMinPQ</c> data type.</summary>
    /// <param name="args">Place holder for user arguments</param>
    ///
    public static void MainTest(string[] args)
    {
        // insert a bunch of strings
        string[] strings =
        {
            "it",
            "was",
            "the",
            "best",
            "of",
            "times",
            "it",
            "was",
            "the",
            "worst"
        };

        IndexMinPQ <string> pq = new IndexMinPQ <string>(strings.Length);

        for (int i = 0; i < strings.Length; i++)
        {
            pq.Insert(i, strings[i]);
        }

        // delete and print each key
        while (!pq.IsEmpty)
        {
            int i = pq.DelMin();
            Console.WriteLine(i + " " + strings[i]);
        }
        Console.WriteLine();

        // reinsert the same strings
        for (int i = 0; i < strings.Length; i++)
        {
            pq.Insert(i, strings[i]);
        }

        // print each key using the iterator
        foreach (int i in pq)
        {
            Console.WriteLine(i + " " + strings[i]);
        }
        while (!pq.IsEmpty)
        {
            Console.WriteLine("Min k={0} at {1}", pq.MinKey, pq.MinIndex);
            Console.WriteLine("Removed {0}", pq.DelMin());
        }
    }
예제 #23
0
        public void Run()
        {
            Console.WriteLine("Choose file:");   // Prompt
            Console.WriteLine("1 - tinyPQ.txt"); // Prompt
            Console.WriteLine("or quit");        // Prompt

            var fileNumber = Console.ReadLine();
            var fieName    = string.Empty;

            switch (fileNumber)
            {
            case "1":
                fieName = "tinyIndexPQ.txt";
                break;

            case "quit":
                return;

            default:
                return;
            }


            var @in   = new In($"Files\\Sorting\\{fieName}");
            var words = @in.ReadAllStrings();

            //var list = words.Select(word => new StringComparable(word)).ToList();

            //var listComparable = list.Cast<IComparable>().ToList();
            //var arrayComparable = list.Cast<IComparable>().ToArray();
            var listStrings = words.ToList();


            var pq = new IndexMinPQ <string>(listStrings.Count);

            //Fill Priority Queue
            for (var i = 0; i < listStrings.Count; i++)
            {
                pq.Insert(i, listStrings[i]);
            }
            // print results
            foreach (var item in pq)
            {
                Console.WriteLine(pq.KeyOf(item));
            }


            Console.ReadLine();
        }
예제 #24
0
        /// <summary>
        /// Compute a minimum spanning tree (or forest) of an edge-weighted graph.
        /// </summary>
        /// <param name="g">g the edge-weighted graph</param>
        public PrimMST(EdgeWeightedGraph g)
        {
            _edgeTo = new EdgeW[g.V];
            _distTo = new double[g.V];
            _marked = new bool[g.V];
            _pq = new IndexMinPQ<Double>(g.V);
            for (var v = 0; v < g.V; v++)
                _distTo[v] = double.PositiveInfinity;

            for (var v = 0; v < g.V; v++)      // run from each vertex to find
                if (!_marked[v]) Prim(g, v);      // minimum spanning forest

            // check optimality conditions
            //assert check(G);
        }
예제 #25
0
        public void IndexMinPQTest1()
        {
            const int    MaxSize  = 8;
            const double MinValue = 3.9;
            const double MaxValue = MinValue * MaxSize + 32;
            int          index;

            // MinValue index == 3, MaxValue index == 4
            double[] items = { MinValue * 2, MinValue * 3, MinValue * 4, MinValue, MaxValue, MinValue * 5, MinValue * 6, MinValue * 7 };
            StdRandom.Seed = 101;

            IndexMinPQ <double> pq = new IndexMinPQ <double>(MaxSize);

            index = StdRandom.Uniform(items.Length);
            Assert.IsFalse(pq.Contains(index));
            Assert.IsTrue(pq.IsEmpty);
            Assert.AreEqual(0, pq.Count);

            try
            {
                index = pq.DelMin();
                Assert.Fail("Failed to catch exception");
            }
            catch (InvalidOperationException) { }

            for (int i = 0; i < items.Length; i++)
            {
                pq.Insert(i, items[i]);
            }
            Assert.AreEqual(items.Length, pq.Count);
            Assert.AreEqual(MinValue, pq.MinKey);
            Assert.AreEqual(3, pq.MinIndex);
            Assert.AreEqual(MaxValue, pq.KeyOf(4));

            index = StdRandom.Uniform(items.Length);
            Assert.AreEqual(items[index], pq.KeyOf(index));

            pq.ChangeKey(1, pq.MinKey * 0.9); // make it the smallest item
            Assert.AreEqual(1, pq.MinIndex);

            pq.DecreaseKey(3, pq.MinKey * 0.87);
            Assert.AreEqual(3, pq.MinIndex);

            pq.Delete(3);
            Assert.AreNotEqual(3, pq.MinIndex);

            Assert.AreEqual(1, pq.DelMin());
        }
예제 #26
0
    // merge together the sorted input streams and write the sorted result to standard output
    private static void merge(In[] streams) {
        int n = streams.length;
        IndexMinPQ<String> pq = new IndexMinPQ<String>(n);
        for (int i = 0; i < n; i++)
            if (!streams[i].isEmpty())
                pq.insert(i, streams[i].readString());

        // Extract and print min and read next from its stream. 
        while (!pq.isEmpty()) {
            StdOut.print(pq.minKey() + " ");
            int i = pq.delMin();
            if (!streams[i].isEmpty())
                pq.insert(i, streams[i].readString());
        }
        StdOut.println();
    }
예제 #27
0
        private IndexMinPQ <double> pq; //有效的横切边

        public PrimeMST(IEdgeWeightGraph 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 IndexMinPQ <double>(G.V);
            distTo[0] = 0.0;
            pq.Insert(0, 0.0); //顶点0权重初始化
            while (!pq.IsEmpty)
            {
                Visit(G, pq.DeleteMin());
            }
        }
예제 #28
0
        public DijkstraAlgorithm(EdgeWeightedDigraph digraph, int source) : base(digraph, source)
        {
            //pq maintain a set of vertex need to deal with.
            IndexMinPQ <double> pq = new IndexMinPQ <double>(digraph.V);

            pq.Insert(source, distTo[source]);

            while (!pq.IsEmpty())
            {
                //when v pops up, the distance and path to v have been confirmed
                int v = pq.DelMin();
                foreach (DirectedEdge e in digraph.Adj(v))
                {
                    Relax(pq, e);
                }
            }
        }
예제 #29
0
        public PrimMST(EdgeWeightedGraph G)
        {
            edgeTo = new Edge[G.v()];
            distTo = new double[G.v()];
            mark   = new bool[G.v()];
            for (int v = 0; v < G.v(); v++)
            {
                distTo[v] = double.MaxValue;
            }
            pq = new IndexMinPQ <double>(4);

            distTo[0] = 0.0;
            pq.insert(0, 0.0);
            while (!pq.isEmpty())
            {
                visit(G, pq.delMin());
            }
        }
예제 #30
0
        private readonly decimal[] _distTo; // distTo[v] = distance  of shortest s->v path

        #endregion Fields

        #region Constructors

        /**
         * Computes a shortest paths tree from <tt>s</tt> to every other vertex in
         * the edge-weighted digraph <tt>G</tt>.
         * @param G the edge-weighted digraph
         * @param s the source vertex
         * @throws IllegalArgumentException if an edge weight is negative
         * @throws IllegalArgumentException unless 0 &le; <tt>s</tt> &le; <tt>V</tt> - 1
         */
        public ShortestNeuronPath(NeuronGraph G, int s)
        {
            _distTo = new decimal[G.V()];
            edgeTo = new DirectedEdge[G.V()];
            for (int v = 0; v < G.V(); v++)
                _distTo[v] = decimal.MaxValue;
            _distTo[s] = 0.0M;

            // relax vertices in order of distance from s
            pq = new IndexMinPQ<decimal>(G.V());
            pq.Insert(s, _distTo[s]);
            while (!pq.IsEmpty())
            {
                int v = pq.DelMin();
                foreach (DirectedEdge e in G.adj(v))
                    relax(e);
            }
        }
예제 #31
0
        void IndexMinPQTest()
        {
            var strArr = FileHandler.ReadFileAsStrArr("words3.txt");

            strArr.Show();
            var pq = new IndexMinPQ <string>(strArr.Length);

            for (int i = 0; i < strArr.Length; i++)
            {
                pq.Insert(i, strArr[i]);
            }
            while (!pq.IsEmpty())
            {
                Console.WriteLine(pq.DelMin());
            }
            Console.WriteLine();
            Console.ReadKey();
        }
예제 #32
0
        public PrimMinSpanningTree(EdgeWeightedGraph g)
        {
            edgeTo     = new Edge[g.VertexCount];
            distanceTo = new double[g.VertexCount];
            marked     = new bool[g.VertexCount];
            pq         = new IndexMinPQ <double>(g.VertexCount);
            for (int i = 0; i < g.VertexCount; i++)
            {
                distanceTo[i] = double.MaxValue;
            }

            distanceTo[0] = 0;
            pq.Insert(0, 0);
            while (!pq.IsEmpty())
            {
                Visit(g, pq.DeleteMin());
            }
        }
예제 #33
0
        public DijkstraShortestPath(EdgeWeightedDirectedGraph graph, int start)
        {
            EdgeTo = new DirectedEdge[graph.VertexCount];
            DistTo = new double[graph.VertexCount];
            pq     = new IndexMinPQ <double>(graph.VertexCount);

            for (int i = 0; i < graph.VertexCount; i++)
            {
                DistTo[i]     = double.PositiveInfinity;
                DistTo[start] = 0;

                pq.Insert(start, 0);
                while (!pq.IsEmpty())
                {
                    Relax(graph, pq.DeleteMin());
                }
            }
        }
예제 #34
0
    public void IndexMinPQ_Dequeue()
    {
        var q = new IndexMinPQ<int>(items.Length);
        for (int i = 0; i < items.Length; i++)
        {
            q.Insert(i, items[i]);
        }

        var sortedItems = new List<int>(items);
        sortedItems.Sort();

        foreach (var item in sortedItems)
        {
            // The top of the queue returns the items in sorted order 
            var minIndex = q.DelMin();
            Assert.AreEqual(items[minIndex], item);
        }
    }
예제 #35
0
        public PrimMST(EdgeWeightedGraph g)
        {
            edgeTo = new Edge[g.V];
            distTo = new double[g.V];
            marked = new bool[g.V];
            pq     = new IndexMinPQ <double>(g.V);
            for (int v = 0; v < g.V; v++)
            {
                distTo[v] = double.PositiveInfinity;
            }

            for (int v = 0; v < g.V; v++)
            {
                if (!marked[v])
                {
                    prim(g, v);
                }
            }
        }
예제 #36
0
        public PrimeMST(EdgeWeightedGraph graph)
        {
            _edgeTo = new Edge[graph.V];
            _distTo = new double[graph.V];
            _marked = new bool[graph.V];

            for (int i = 0; i < graph.V; i++)
            {
                _distTo[i] = double.PositiveInfinity;
            }
            _pq = new IndexMinPQ <double>(graph.V);

            _distTo[0] = 0.0;
            _pq.insert(0, 0.0);
            while (!_pq.isEmpty())
            {
                Visit(graph, _pq.delMin());
            }
        }
예제 #37
0
        public KruskalMinSpanningTree(EdgeWeightedGraph g)
        {
            mst = new Queue <Edge>();
            IndexMinPQ <Edge> pq = new IndexMinPQ <Edge>(g.EdgeCount);
            UnionFind_1       uf = new UnionFind_1(g.VertexCount);

            while (!pq.IsEmpty() && mst.Count < g.VertexCount - 1)
            {
                Edge e  = pq.DelMin();
                int  v1 = e.V1;
                int  v2 = e.Other(v1);
                if (uf.Connected(v1, v2))
                {
                    continue;
                }

                uf.Union(v1, v2);
                mst.Enqueue(e);
            }
        }
예제 #38
0
        public DijkstraSP(EdgeWeightedDigraph graph, int startVertex)
        {
            edgeTo        = new DirectedEdge[graph.Vertices];
            distTo        = new double[graph.Vertices];
            priorityQueue = new IndexMinPQ <double>(graph.Vertices);

            for (int v = 0; v < graph.Vertices; v++)
            {
                distTo[v] = double.MaxValue;
            }

            distTo[startVertex] = 0.0f;

            priorityQueue.Insert(startVertex, 0.0f);

            while (!priorityQueue.IsEmpty())
            {
                Relax(graph, priorityQueue.DelMin());
            }
        }
예제 #39
0
        protected void Relax(IndexMinPQ <double> pq, DirectedEdge e)
        {
            int v = e.From;
            int w = e.To;

            if (distTo[w] > distTo[v] + e.Weight)
            {
                distTo[w] = distTo[v] + e.Weight;
                edgeTo[w] = e;
                if (pq.Contains(w))
                {
                    pq.DecreaseKey(w, distTo[w]);
                }
                else
                {
                    //this will never used
                    pq.Insert(w, distTo[w]);
                }
            }
        }
예제 #40
0
        public DijkstraSP(EdgeWeightedDigraph g, int s)
        {
            this._g = g;
            this._s = s;
            this.DistTo = new double[g.V()];
            this._edgeTo = new DirectedEdge[g.V()];
            this._pq = new IndexMinPQ<double>(g.V());

            for (int v = 0; v < g.V(); v++)
                this.DistTo[v] = double.PositiveInfinity;
            this.DistTo[s] = 0d;

            this._pq.Insert(s, 0d);
            while (!this._pq.IsEmpty())
            {
                int v = this._pq.DelMin();
                foreach (DirectedEdge e in g.Adj[v])
                    this.relax(e);
            }
        }
예제 #41
0
        public PrimMst(EdgeWeightedGraph graph)
        {
            edgeTo = new Edge[graph.Vertices];
            distTo = new double[graph.Vertices];
            marked = new bool[graph.Vertices];

            for (int vertex = 0; vertex < graph.Vertices; vertex++)
            {
                distTo[vertex] = double.MaxValue;
            }

            prioryQueue = new IndexMinPQ <double>(graph.Vertices);

            distTo[0] = 0.0f;
            prioryQueue.Insert(0, 0.0f);

            while (!prioryQueue.IsEmpty())
            {
                Visit(graph, prioryQueue.DelMin());
            }
        }
예제 #42
0
 public void DifkstraSPMy(EdgeWeightedDigraph g, int s)
 {
     _edgeTo    = new DirectedEdge[g.V];
     _distTo    = Enumerable.Repeat(double.PositiveInfinity, g.V).ToArray();
     _distTo[s] = 0.0;
     _pq        = new IndexMinPQ <double>(g.V);
     foreach (var e in g.Adj(s))
     {
         _edgeTo[e.To] = e;
         _distTo[e.To] = e.Weight;
         _pq.Insert(e.To, e.Weight);
     }
     while (!_pq.IsEmpty())
     {
         var i = _pq.DelMin();
         foreach (var e in g.Adj(i))
         {
             RelaxMy(i, e);
         }
     }
 }