Exemplo n.º 1
0
        public LazyPrimMST(EdgeWeightedGraph graph)
        {
            prioryQueue = new MinPQ <Edge>();
            marked      = new bool[graph.Vertecies];
            mst         = new Queue <Edge>();

            Visit(graph, 0);

            while (!prioryQueue.IsEmpty())
            {
                var edge        = prioryQueue.DelMin();
                int vertex      = edge.Either();
                int otherVertex = edge.Other(vertex);

                if (marked[vertex] && marked[otherVertex])
                {
                    continue;
                }

                mst.Enqueue(edge);
                if (!marked[vertex])
                {
                    Visit(graph, vertex);
                }
                if (!marked[otherVertex])
                {
                    Visit(graph, otherVertex);
                }
            }
        }
Exemplo n.º 2
0
        public KruskalMst(EdgeWeightedGraph graph)
        {
            mst = new Queue <Edge>();

            var prioryQueue = new MinPQ <Edge>();

            foreach (var edge in graph.GetEdges())
            {
                prioryQueue.Insert(edge);
            }

            var ds = new DisjointSet(graph.Vertices);

            while (!prioryQueue.IsEmpty() && mst.Count < graph.Vertices - 1)
            {
                var edge        = prioryQueue.DelMin();
                int vertex      = edge.Either();
                int otherVertex = edge.Other(vertex);

                if (ds.Connected(vertex, otherVertex))
                {
                    continue;
                }

                ds.Union(vertex, otherVertex);
                mst.Enqueue(edge);
            }
        }
    public KruskalMST(EdgeWeightedGraph ewg)
    {
        this.mst = new Queue();
        MinPQ    minPQ    = new MinPQ();
        Iterator iterator = ewg.edges().iterator();

        while (iterator.hasNext())
        {
            Edge edge = (Edge)iterator.next();
            minPQ.insert(edge);
        }
        UF uF = new UF(ewg.V());

        while (!minPQ.isEmpty() && this.mst.size() < ewg.V() - 1)
        {
            Edge edge = (Edge)minPQ.delMin();
            int  num  = edge.either();
            int  i    = edge.other(num);
            if (!uF.connected(num, i))
            {
                uF.union(num, i);
                this.mst.enqueue(edge);
                this.weight += edge.weight();
            }
        }
        if (!KruskalMST.s_assertionsDisabled && !this.check(ewg))
        {
            throw new AssertionError();
        }
    }
Exemplo n.º 4
0
 public void Initialize()
 {
     _target = new MinPQ<Distance>();
     _target.Insert(new Distance { V = 0, Dist = 3 });
     _target.Insert(new Distance { V = 1, Dist = 1 });
     _target.Insert(new Distance { V = 2, Dist = 2 });
 }
Exemplo n.º 5
0
        public KruskalMST(EdgeWeightedGraph G)
        {
            _mst = new Queue <Edge>();
            var pq = new MinPQ <Edge>(G.Edges().Count());
            var uf = new WeightedQuickUnion(G.V);

            foreach (var edge in G.Edges())
            {
                if (edge is null)
                {
                    continue;
                }
                pq.Insert(edge);
            }
            while (!pq.IsEmpty && _mst.Count() < G.V - 1)
            {
                var e = pq.DelMin(); // Get min weight edge on pq
                var v = e.Either();
                var w = e.Other(v);  // and its vertices.
                if (uf.Connected(v, w))
                {
                    continue;    // Ignore ineligible edges.
                }
                uf.Union(v, w);  // Merge components.
                _mst.Enqueue(e); // Add edge to mst.
            }
        }
        private KruskalMSTAlgorithm(EdgeWeightedGraph graph)
        {
            // It is more efficient to build a heap by passing array of edges.
            MinPQ <Edge> crossingEdgesByWeight = new MinPQ <Edge>(1);

            this._mst = new Queue <Edge>();

            foreach (Edge edge in graph.GetEdges())
            {
                crossingEdgesByWeight.Add(edge);
            }

            // Greedy algorithm
            UnionFinder uf = new UnionFinder(graph.VerticesCount);

            while (!crossingEdgesByWeight.IsEmpty && this._mst.Count < graph.VerticesCount - 1)
            {
                Edge edge = crossingEdgesByWeight.DeleteMin();

                Int32 sourceVertice = edge.Source;
                Int32 targetVertice = edge.Target;

                if (!uf.IsConnected(sourceVertice, targetVertice))
                {
                    // sourceVertice - targetVertice does not create a cycle.
                    uf.Union(sourceVertice, targetVertice); // Merge sourcerVertice and targetVertice components.

                    this._mst.Enqueue(edge);                // Add edge to minimum spanning tree.

                    this.Weight += edge.Weight;
                }
            }
        }
Exemplo n.º 7
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 KruskalMST(EdgeWeightedGraph g)
        {
            // more efficient to build heap by passing array of edges
            var pq = new MinPQ<EdgeW>();
            foreach (var e in g.Edges())
            {
                pq.Insert(e);
            }

            // run greedy algorithm
            var uf = new UF(g.V);
            while (!pq.IsEmpty() && _mst.Size() < g.V - 1)
            {
                var e = pq.DelMin();
                var v = e.Either();
                var w = e.Other(v);
                if (!uf.Connected(v, w))
                { // v-w does not create a cycle
                    uf.Union(v, w);  // merge v and w components
                    _mst.Enqueue(e);  // add edge e to mst
                    _weight += e.Weight;
                }
            }

            // check optimality conditions
            //assert check(G);
        }
Exemplo n.º 8
0
        public static void Main(string[] arg)
        {
            string filename = "words3.txt";
            string[] a = Util.readWords(filename);

            MaxPQ<string> pqMax = new MaxPQ<string>();

            foreach (var item in a)
            {
                pqMax.insert(item);
            }
            // se vor afisa cuvintele in ordine descrescatoare
            Console.WriteLine("MaxPQ");
            while (!pqMax.isEmpty())
            {
                Console.WriteLine(pqMax.delMax());
            }

            MinPQ<string> pqMin = new MinPQ<string>();
            foreach (var item in a)
            {
                pqMin.insert(item);
            }
            // se vor afisa cuvintele in ordine crescatoare
            Console.WriteLine("\nMinPQ");
            while (!pqMin.isEmpty())
            {
                Console.WriteLine(pqMin.delMin());
            }
        }
Exemplo n.º 9
0
    /**
     * Simulates the system of particles for the specified amount of time.
     *
     * @param  limit the amount of time
     */
    public void simulate(double limit) {
        
        // initialize PQ with collision events and redraw event
        pq = new MinPQ<Event>();
        for (int i = 0; i < particles.length; i++) {
            predict(particles[i], limit);
        }
        pq.insert(new Event(0, null, null));        // redraw event


        // the main event-driven simulation loop
        while (!pq.isEmpty()) { 

            // get impending event, discard if invalidated
            Event e = pq.delMin();
            if (!e.isValid()) continue;
            Particle a = e.a;
            Particle b = e.b;

            // physical collision, so update positions, and then simulation clock
            for (int i = 0; i < particles.length; i++)
                particles[i].move(e.time - t);
            t = e.time;

            // process event
            if      (a != null && b != null) a.bounceOff(b);              // particle-particle collision
            else if (a != null && b == null) a.bounceOffVerticalWall();   // particle-wall collision
            else if (a == null && b != null) b.bounceOffHorizontalWall(); // particle-wall collision
            else if (a == null && b == null) redraw(limit);               // redraw event

            // update the priority queue with new collisions involving a or b
            predict(a, limit);
            predict(b, limit);
        }
    }
Exemplo n.º 10
0
        public LazyPrimMST(EdgeWeightedGraph g)
        {
            _pq     = new MinPQ <Edge>(g.E);
            _marked = new List <bool>(new bool[g.V]);
            _mst    = new Queue <Edge>();

            Visit(g, 0);
            while (!_pq.IsEmpty)
            {
                var e = (Edge)_pq.DeleteMin();
                int v = e.Either(), 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);
                }
            }
        }
Exemplo n.º 11
0
    private Queue <Edge> mst = new Queue <Edge>(); // edges in MST



    public KruskalMST(EdgeWeightedGraph G)
    {
        // more efficient to build heap by passing array of edges

        EdgeComparer comparer = new EdgeComparer();
        MinPQ <Edge> pq       = new MinPQ <Edge>((Comparer <Edge>)comparer);

        foreach (Edge e in G.edges())
        {
            pq.insert(e);
        }

        // run greedy algorithm
        UF uf = new UF(G.V());

        while (!pq.isEmpty() && mst.size() < G.V() - 1)
        {
            Edge e = pq.delMin();
            int  v = e.either();
            int  w = e.other(v);
            if (!uf.connected(v, w))
            {                   // v-w does not create a cycle
                uf.union(v, w); // merge v and w components
                mst.Enqueue(e); // add edge e to mst
                weight += e.Weight();
            }
        }
    }
        static void Main(string[] args)
        {
            var processorNum = int.Parse(Console.ReadLine());
            var jobNum       = int.Parse(Console.ReadLine());

            var jobs = new Job[jobNum];

            for (var i = 0; i < jobNum; i++)
            {
                var jobDesc = Console.ReadLine().Split(' ');
                jobs[i] = new Job(jobDesc[0], double.Parse(jobDesc[1]));
            }

            Array.Sort(jobs);

            var processors = new MinPQ <Processor>(processorNum);

            for (var i = 0; i < processorNum; i++)
            {
                processors.Insert(new Processor());
            }

            for (var i = jobs.Length - 1; i >= 0; i--)
            {
                var min = processors.DelMin();
                min.Add(jobs[i]);
                processors.Insert(min);
            }

            while (!processors.IsEmpty())
            {
                Console.WriteLine(processors.DelMin());
            }
        }
Exemplo n.º 13
0
            /// <summary>
            /// 向下访问叶节点,并将slide添加到优先列表中
            /// </summary>
            /// <param name="node"></param>
            /// <param name="p"></param>
            /// <param name="pq"></param>
            /// <returns></returns>
            private TreeNode Explore2Leaf(TreeNode node, Point p, MinPQ pq)
            {
                TreeNode unexpl;
                var      expl = node;
                TreeNode prev;

                while (expl != null && (expl.left != null || expl.right != null))
                {
                    prev = expl;
                    var axis = expl.axis;
                    var val  = expl.point.vector[axis];

                    if (p.vector[axis] <= val)
                    {
                        unexpl = expl.right;
                        expl   = expl.left;
                    }
                    else
                    {
                        unexpl = expl.left;
                        expl   = expl.right;
                    }
                    if (unexpl != null)
                    {
                        pq.insert(new PQNode(unexpl, Math.Abs(val - p.vector[axis])));
                    }
                    if (expl == null)
                    {
                        return(prev);
                    }
                }
                return(expl);
            }
Exemplo n.º 14
0
        private readonly Collections.Queue <EdgeW> _mst = new Collections.Queue <EdgeW>(); // edges in MST

        /// <summary>
        /// Compute a minimum spanning tree (or forest) of an edge-weighted graph.
        /// </summary>
        /// <param name="g">g the edge-weighted graph</param>
        public KruskalMST(EdgeWeightedGraph g)
        {
            // more efficient to build heap by passing array of edges
            var pq = new MinPQ <EdgeW>();

            foreach (var e in g.Edges())
            {
                pq.Insert(e);
            }

            // run greedy algorithm
            var uf = new UF(g.V);

            while (!pq.IsEmpty() && _mst.Size() < g.V - 1)
            {
                var e = pq.DelMin();
                var v = e.Either();
                var w = e.Other(v);
                if (!uf.Connected(v, w))
                {                    // v-w does not create a cycle
                    uf.Union(v, w);  // merge v and w components
                    _mst.Enqueue(e); // add edge e to mst
                    _weight += e.Weight;
                }
            }

            // check optimality conditions
            //assert check(G);
        }
Exemplo n.º 15
0
        public Kruskal(WeightedGraph G)
        {
            var V  = G.V();
            var uf = new QuickUnion(V);

            var pq = new MinPQ <Edge>();

            mst = new List <Edge>();
            foreach (Edge e in G.edges())
            {
                pq.Enqueue(e);
            }

            while (!pq.IsEmpty && mst.Count < V - 1)
            {
                var e = pq.DelMin();
                var v = e.either();
                var w = e.other(v);

                if (!uf.IsConnected(v, w))
                {
                    uf.Union(v, w);
                    mst.Add(e);
                }
            }
        }
Exemplo n.º 16
0
        public void Test_Empty_OnCreation()
        {
            MinPQ <Int32> pq = new MinPQ <Int32>(1);

            Assert.True(pq.IsEmpty);
            Assert.Equal(0, pq.Count);
        }
Exemplo n.º 17
0
        public static void Main(string[] args)
        {
            int M = 5;
            MinPQ<int> pq = new MinPQ<int>(M + 1);

            //StreamReader fs = new StreamReader("tinyW.txt");
            //StreamReader fs = new StreamReader("tinyT.txt");
            //StreamReader fs = new StreamReader("largeW.txt");
            StreamReader fs = new StreamReader("largeT.txt");
            string line;
            while (!fs.EndOfStream)
            {
                line = fs.ReadLine();
                pq.insert(int.Parse(line));

                // eliminam valoarea minima din coada cu prioritate daca sunt M+1 elemente in coada
                if (pq.size() > M)
                    pq.delMin();
            } // cele mai mari M elemente sunt in coada

            // afisam elementele din coada cu prioritate in ordine inversa
            Stack<int> stack = new Stack<int>();
            foreach (var item in pq)
                stack.push(item);

            foreach (var item in stack)
            {
                Console.WriteLine(item);
            }
        }
Exemplo n.º 18
0
        public void MinPQTest()
        {
            string[] graphItems = {
                "4 5 0.35",
                "4 7 0.37",
                "5 7 0.28",
                "0 7 0.16",
                "1 5 0.32",
                "0 4 0.38",
                "2 3 0.17",
                "1 7 0.19",
                "0 2 0.26",
                "1 2 0.36",
                "1 3 0.29",
                "2 7 0.34",
                "6 2 0.40",
                "3 6 0.52",
                "6 0 0.58",
                "6 4 0.93"
            };
            var graph = new EdgeWeightedGraph(8, 16, graphItems);

            var pq = new MinPQ<Edge>();

            foreach (Edge edge in graph.Edges())
            {
                pq.insert(edge);
            }

            while (pq.isEmpty() == false)
            {
                pq.delMin();
            }
        }
Exemplo n.º 19
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);
         }
     }
 }
 public MaxPQWithSize(int max, IComparer <T> comparer)
 {
     //m_pq = new T[max + 2];
     m_max      = max;
     m_minPQ    = new MinPQ <T>(max, comparer);
     m_comparer = comparer;
 }
Exemplo n.º 21
0
        public KruskalMST(EdgeWeightedGraph ewg)
        {
            this.g   = ewg;
            minPQ    = new MinPQ <Edge>(g.E());
            mstEdges = new Queue <Edge>();
            //first we need to create a priority queue to store all Edges

            int either, other;

            foreach (Edge edge in ewg.Edges())
            {
                //either = edge.Either();
                //other = edge.Other(either);
                //if(either<other) //insert the same edge once only when either<other;
                minPQ.Insert(edge);
            }
            Edge currrent;

            Utils.UF uf = new Utils.UF(g.V()); //instantiate the union find variable

            //second, we take min from the PQ one at a time and insert to the queue if both ends are not connected yet
            while (!minPQ.IsEmpty() && mstEdges.Count < (this.g.V() - 1))
            {
                currrent = minPQ.DelMin();
                either   = currrent.Either();
                other    = currrent.Other(either);
                if (!uf.IsConnected(either, other)) //only add the edge into the final queue if both ends are not connected
                {
                    mstEdges.Enqueue(currrent);
                    uf.Union(either, other);
                }
            }
        }
Exemplo n.º 22
0
    static T ExtractMin <T>(MinPQ <T> pq) where T : IComparable <T>
    {
        T x = pq.Top;

        pq.Pop();
        return(x);
    }
Exemplo n.º 23
0
        /// <summary>
        /// Returns a uniformly random tree on <tt>V</tt> vertices.
        /// This algorithm uses a Prufer sequence and takes time proportional to <em>V log V</em>.
        /// http://www.proofwiki.org/wiki/Labeled_Tree_from_Prüfer_Sequence
        /// http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.36.6484&rep=rep1&type=pdf
        /// </summary>
        /// <param name="v">V the number of vertices in the tree</param>
        /// <returns>a uniformly random tree on <tt>V</tt> vertices</returns>
        public static Graph Tree(int v)
        {
            var g = new Graph(v);

            // special case
            if (v == 1)
            {
                return(g);
            }

            // Cayley's theorem: there are V^(V-2) labeled trees on V vertices
            // Prufer sequence: sequence of V-2 values between 0 and V-1
            // Prufer's proof of Cayley's theorem: Prufer sequences are in 1-1
            // with labeled trees on V vertices
            var prufer = new int[v - 2];

            for (var i = 0; i < v - 2; i++)
            {
                prufer[i] = StdRandom.Uniform(v);
            }

            // degree of vertex v = 1 + number of times it appers in Prufer sequence
            var degree = new int[v];

            for (var vi = 0; vi < v; vi++)
            {
                degree[vi] = 1;
            }
            for (var i = 0; i < v - 2; i++)
            {
                degree[prufer[i]]++;
            }

            // pq contains all vertices of degree 1
            var pq = new MinPQ <Integer>();

            for (var vi = 0; vi < v; vi++)
            {
                if (degree[vi] == 1)
                {
                    pq.Insert(vi);
                }
            }

            // repeatedly delMin() degree 1 vertex that has the minimum index
            for (var i = 0; i < v - 2; i++)
            {
                int vmin = pq.DelMin();
                g.AddEdge(vmin, prufer[i]);
                degree[vmin]--;
                degree[prufer[i]]--;
                if (degree[prufer[i]] == 1)
                {
                    pq.Insert(prufer[i]);
                }
            }
            g.AddEdge(pq.DelMin(), pq.DelMin());
            return(g);
        }
        public void Hamlet_MinPQ()
        {
            // arrange
            var pq = new MinPQ <string>();

            // act
            ArrayPQHamlet(pq, new[] { "be", "be", "not", "or", "that", "to" }, new[] { "is", "to" });
        }
Exemplo n.º 25
0
 public LazyPrimMST(EdgeWeightedGraph g)
 {
     this.MST = new Queue<Edge>();
     this._pq = new MinPQ<Edge>();
     this._marked = new bool[g.V()];
     for (int v = 0; v < g.V(); v++)
         if (!this._marked[v])
             this.prim(g, v);
 }
Exemplo n.º 26
0
    private MinPQ<Edge> pq;      // edges with one endpoint in tree

    /**
     * Compute a minimum spanning tree (or forest) of an edge-weighted graph.
     * @param G the edge-weighted graph
     */
    public LazyPrimMST(EdgeWeightedGraph G) {
        mst = new Queue<Edge>();
        pq = new MinPQ<Edge>();
        marked = new boolean[G.V()];
        for (int v = 0; v < G.V(); v++)     // run Prim from all vertices to
            if (!marked[v]) prim(G, v);     // get a minimum spanning forest

        // check optimality conditions
        assert check(G);
    }
Exemplo n.º 27
0
        public void Test_NotEmpty_WhenAdding()
        {
            MinPQ <Int32> pq = new MinPQ <Int32>(2);

            pq.Add(18);
            pq.Add(2);

            Assert.False(pq.IsEmpty);
            Assert.Equal(2, pq.Count);
        }
Exemplo n.º 28
0
        public void Test_Empty_WhenCleaning()
        {
            MinPQ <Int32> pq = new MinPQ <Int32>(1);

            pq.Add(2);
            pq.DeleteMin();

            Assert.True(pq.IsEmpty);
            Assert.Equal(0, pq.Count);
        }
Exemplo n.º 29
0
        private double _weight; // total weight of MST

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Compute a minimum spanning tree (or forest) of an edge-weighted graph.
        /// </summary>
        /// <param name="g">g the edge-weighted graph</param>
        public LazyPrimMST(EdgeWeightedGraph g)
        {
            _mst = new Collections.Queue<EdgeW>();
            _pq = new MinPQ<EdgeW>();
            _marked = new bool[g.V];
            for (var v = 0; v < g.V; v++)     // run Prim from all vertices to
                if (!_marked[v]) Prim(g, v);     // get a minimum spanning forest

            // check optimality conditions
            //assert check(G);
        }
Exemplo n.º 30
0
        public void ShouldReturnSize(int[] values, int expectedCount)
        {
            // Arrange
            var minPQ = new MinPQ <int>(values);

            // Act
            var actualCount = minPQ.Size();

            // Assert
            Assert.AreEqual(expectedCount, actualCount);
        }
Exemplo n.º 31
0
        public void Test_Add_Min()
        {
            MinPQ <Int32> pq = new MinPQ <Int32>(10);

            for (int i = 1; i < 11; i++)
            {
                pq.Add(i);
            }

            Assert.Equal(1, pq.Min());
        }
Exemplo n.º 32
0
        public void ShouldReturnTrueIfMinPqIsEmpty()
        {
            // Arrange
            var minPQ = new MinPQ <int>();

            // Act
            var result = minPQ.IsEmpty();

            // Assert
            Assert.IsTrue(result);
        }
Exemplo n.º 33
0
 public EagerPrimMST(EdgeWeightedGraph g)
 {
     _edgeTo = new Edge[g.V()];
     _distTo = new double[g.V()];
     for (var i = 0; i < g.V(); i++)
     {
         _distTo[i] = double.PositiveInfinity;
     }
     _marked = new bool[g.V()];
     _pq     = new MinPQ <double>(g.E());
     Visit(g, 0);
 }
        static void Main(string[] args)
        {
            // 输入格式: buy 20.05 100
            var buyer  = new MaxPQ <Ticket>();
            var seller = new MinPQ <Ticket>();

            var n = int.Parse(Console.ReadLine());

            for (var i = 0; i < n; i++)
            {
                var ticket = new Ticket();
                var item   = Console.ReadLine().Split(' ');

                ticket.Price = double.Parse(item[1]);
                ticket.Share = int.Parse(item[2]);
                if (item[0] == "buy")
                {
                    buyer.Insert(ticket);
                }
                else
                {
                    seller.Insert(ticket);
                }
            }

            while (!buyer.IsEmpty() && !seller.IsEmpty())
            {
                if (buyer.Max().Price < seller.Min().Price)
                {
                    break;
                }
                var buy  = buyer.DelMax();
                var sell = seller.DelMin();
                Console.Write("sell $" + sell.Price + " * " + sell.Share);
                if (buy.Share > sell.Share)
                {
                    Console.WriteLine(" -> " + sell.Share + " -> $" + buy.Price + " * " + buy.Share + " buy");
                    buy.Share -= sell.Share;
                    buyer.Insert(buy);
                }
                else if (buy.Share < sell.Share)
                {
                    sell.Share -= buy.Share;
                    seller.Insert(sell);
                    Console.WriteLine(" -> " + buy.Share + " -> $" + buy.Price + " * " + buy.Share + " buy");
                }
                else
                {
                    Console.WriteLine(" -> " + sell.Share + " -> $" + buy.Price + " * " + buy.Share + " buy");
                }
            }
        }
Exemplo n.º 35
0
        public void ShouldReturnFalseIfMinPqIsNotEmpty()
        {
            // Arrange
            var minPQ = new MinPQ <int>();

            minPQ.Insert(5);

            // Act
            var result = minPQ.IsEmpty();

            // Assert
            Assert.IsFalse(result);
        }
Exemplo n.º 36
0
        public void TestMinPQ() {
            var arr = CreateRandomArray(10);
            Insertion<int>.Sort(arr);
            StdOut.WriteLine(arr);

            var pq = new MinPQ<int>();
            foreach (int i in arr) {
                pq.Insert(i);
            }

            while (!pq.IsEmpty) {
                StdOut.WriteLine("delete min: {0}", pq.DelMin());
            }
        }
Exemplo n.º 37
0
        public Dijkstra(EdgeWeightedDigraph graph, int source)
        {
            pq     = new MinPQ <double>(graph.V());
            edgeTo = new DirectedWeightedEdge[graph.V()];
            distTo = new double[graph.V()];

            for (int i = 0; i < graph.V(); ++i)
            {
                distTo[i] = double.MaxValue;
            }
            distTo[source] = 0.0;

            dijkstra(graph, 0);
        }
Exemplo n.º 38
0
 public void Min_pq_delete_tests()
 {
     var p = new MinPQ<int>(5);
     p.Insert(5);
     p.Insert(4);
     p.Insert(99);
     p.Insert(14);
     p.Insert(0);
     Assert.AreEqual(0, p.DelMin());
     Assert.AreEqual(4, p.DelMin());
     Assert.AreEqual(5, p.DelMin());
     Assert.AreEqual(14, p.DelMin());
     Assert.AreEqual(99, p.DelMin());
 }
Exemplo n.º 39
0
        public Astar(EdgeWeightedDigraph graph, int source, int target)
        {
            pq     = new MinPQ <double>(graph.V());
            edgeTo = new DirectedWeightedEdge[graph.V()];
            distTo = new double[graph.V()];

            for (int i = 0; i < graph.V(); ++i)
            {
                distTo[i] = double.MaxValue;
            }
            distTo[source] = 0.0;

            AstarSP(graph, 0, target);
        }
Exemplo n.º 40
0
        public void Min_priority_queue()
        {
            var p = new MinPQ<int>(5);
            p.Insert(5);
            Assert.AreEqual("5", string.Join(",", p.CurrentPQ()));

            p.Insert(4);
            Assert.AreEqual("4,5", string.Join(",", p.CurrentPQ()));

            p.Insert(99);
            Assert.AreEqual("4,5,99", string.Join(",", p.CurrentPQ()));

            p.Insert(14);
            Assert.AreEqual("4,5,99,14", string.Join(",", p.CurrentPQ()));

            p.Insert(0);
            Assert.AreEqual("0,4,99,14,5", string.Join(",", p.CurrentPQ()));
        }
Exemplo n.º 41
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 = "tinyPQ.txt";
                    break;
                case "quit":
                    return;
                default:
                    return;
            }

            var @in = new In(string.Format("Files\\Sorting\\{0}", 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 MinPQ<string>(new StringComparer());
            //Fill Priority Queue
            foreach (var word in listStrings)
            {
                pq.Insert(word);
            }
            // print results
            foreach (var item in pq)
            {
                Console.WriteLine(item);
            }

            Console.ReadLine();
        }
Exemplo n.º 42
0
        public KruskalMST(EdgeWeightedGraph g)
        {
            MinPQ<Edge> pq = new MinPQ<Edge>();
            foreach (Edge e in g.Edges())
                pq.Insert(e);

            Part1.QuickUnion uf = new Part1.QuickUnion(g.V());
            while (!pq.IsEmpty() && this._mst.Count < g.V() - 1)
            {
                Edge e = pq.DelMin();
                int v = e.Either();
                int w = e.Other(v);
                if (!uf.IsConnected(v, w))
                {
                    uf.Union(v, w);
                    this._mst.Enqueue(e);
                    this.Weight += e.Weight();
                }
            }
        }
Exemplo n.º 43
0
        public LazyPrimMST(EdgeWeightedGraph graph)
        {
            pq = new MinPQ<Edge>();
            marked = new bool[graph.V];
            mst = new Queue<Edge>();

            visit(graph, 0);

            while (!pq.isEmpty())
            {
                Edge e = pq.delMin();

                int v = e.Either, w = e.Other(v);

                if (marked[v] && marked[w]) continue;
                mst.Enqueue(e);
                if (!marked[v]) visit(graph, v);
                if (!marked[w]) visit(graph, w);
            }
        }
Exemplo n.º 44
0
	public IEnumerable<int> KSE_MinHeap(int[] A, int K){
		var heap = new int[K];
		for(int i=0; i<heap.Length; i++)
			heap[i] = A[i];
		var pq = new MinPQ(heap);
		for(int i=K; i<A.Length; i++)
			pq.InsertAtTop(A[i]);
		foreach(var i in pq.PQ())
			yield return i;
	}
Exemplo n.º 45
0
		public static void Test(){
			var a = new int[] { 23, 12, 9, 30, 2, 1, 50 };
			MinPQ pq = new MinPQ(a);
			foreach(var i in pq.PQ()){
				Out(i+" ");
			}
		}
Exemplo n.º 46
0
        /// <summary>
        /// Returns a uniformly random tree on <tt>V</tt> vertices.
        /// This algorithm uses a Prufer sequence and takes time proportional to <em>V log V</em>.
        /// http://www.proofwiki.org/wiki/Labeled_Tree_from_Prüfer_Sequence
        /// http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.36.6484&rep=rep1&type=pdf
        /// </summary>
        /// <param name="v">V the number of vertices in the tree</param>
        /// <returns>a uniformly random tree on <tt>V</tt> vertices</returns>
        public static Graph Tree(int v)
        {
            var g = new Graph(v);

            // special case
            if (v == 1) return g;

            // Cayley's theorem: there are V^(V-2) labeled trees on V vertices
            // Prufer sequence: sequence of V-2 values between 0 and V-1
            // Prufer's proof of Cayley's theorem: Prufer sequences are in 1-1
            // with labeled trees on V vertices
            var prufer = new int[v - 2];
            for (var i = 0; i < v - 2; i++)
                prufer[i] = StdRandom.Uniform(v);

            // degree of vertex v = 1 + number of times it appers in Prufer sequence
            var degree = new int[v];
            for (var vi = 0; vi < v; vi++)
                degree[vi] = 1;
            for (var i = 0; i < v - 2; i++)
                degree[prufer[i]]++;

            // pq contains all vertices of degree 1
            var pq = new MinPQ<Integer>();
            for (var vi = 0; vi < v; vi++)
                if (degree[vi] == 1) pq.Insert(vi);

            // repeatedly delMin() degree 1 vertex that has the minimum index
            for (var i = 0; i < v - 2; i++)
            {
                int vmin = pq.DelMin();
                g.AddEdge(vmin, prufer[i]);
                degree[vmin]--;
                degree[prufer[i]]--;
                if (degree[prufer[i]] == 1) pq.Insert(prufer[i]);
            }
            g.AddEdge(pq.DelMin(), pq.DelMin());
            return g;
        }
Exemplo n.º 47
0
 public TopM(ICollection<string> a)
 {
     _m = a.Count;
     _pq = new MinPQ<Transaction>(_m + 1);
     InsertTransactions(a);
 }