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(); } }
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); } }
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(); } }
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()); } }
/// <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); }
/** * 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); } }
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(); } } }
// updates priority queue with all new events for particle a private void predict(Particle a, double limit) { if (a == null) return; // particle-particle collisions for (int i = 0; i < particles.length; i++) { double dt = a.timeToHit(particles[i]); if (t + dt <= limit) pq.insert(new Event(t + dt, a, particles[i])); } // particle-wall collisions double dtX = a.timeToHitVerticalWall(); double dtY = a.timeToHitHorizontalWall(); if (t + dtX <= limit) pq.insert(new Event(t + dtX, a, null)); if (t + dtY <= limit) pq.insert(new Event(t + dtY, null, a)); }
private void scan(EdgeWeightedGraph G, int v) { marked[v] = true; foreach (Edge e in G.Adj(v)) { if (!marked[e.other(v)]) { pq.insert(e); } } }
// build the Huffman trie given frequencies private static Node buildTrie(int[] freq) { // initialze priority queue with singleton trees MinPQ<Node> pq = new MinPQ<Node>(); for (char i = 0; i < R; i++) if (freq[i] > 0) pq.insert(new Node(i, freq[i], null, null)); // special case in case there is only one character with a nonzero frequency if (pq.size() == 1) { if (freq['\0'] == 0) pq.insert(new Node('\0', 0, null, null)); else pq.insert(new Node('\1', 0, null, null)); } // merge two smallest trees while (pq.size() > 1) { Node left = pq.delMin(); Node right = pq.delMin(); Node parent = new Node('\0', left.freq + right.freq, left, right); pq.insert(parent); } return pq.delMin(); }
// 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 /** * Returns a uniformly random tree on {@code V} vertices. * This algorithm uses a Prufer sequence and takes time proportional to <em>V log V</em>. * @param V the number of vertices in the tree * @return a uniformly random tree on {@code V} vertices */ public static Graph tree(int V) { Graph 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 int[] prufer = new int[V-2]; for (int i = 0; i < V-2; i++) prufer[i] = StdRandom.uniform(V); // degree of vertex v = 1 + number of times it appers in Prufer sequence int[] degree = new int[V]; for (int v = 0; v < V; v++) degree[v] = 1; for (int i = 0; i < V-2; i++) degree[prufer[i]]++; // pq contains all vertices of degree 1 MinPQ<Integer> pq = new MinPQ<Integer>(); for (int v = 0; v < V; v++) if (degree[v] == 1) pq.insert(v); // repeatedly delMin() degree 1 vertex that has the minimum index for (int i = 0; i < V-2; i++) { int v = pq.delMin(); G.addEdge(v, prufer[i]); degree[v]--; degree[prufer[i]]--; if (degree[prufer[i]] == 1) pq.insert(prufer[i]); } G.addEdge(pq.delMin(), pq.delMin()); return G; }
public Solver(Board initial) { MinPQ <Move> moves = new MinPQ <Move>(); moves.insert(new Move(initial)); MinPQ <Move> twinMoves = new MinPQ <Move>(); twinMoves.insert(new Move(initial.twin())); while (true) { lastMove = expand(moves); if (lastMove != null || expand(twinMoves) != null) { return; } } }
/// <summary> /// 搜索k近邻点 /// </summary> /// <param name="p"></param> /// <param name="k"></param> /// <returns></returns> public List <TreeNode> BBFSearchKNearest(Point p, int k) { var list = new List <BBFData>(); // var pq = new MinPQ(); pq.insert(new PQNode(root, 0)); int t = 0; while (pq.nodes.Count > 0 && t < max_nn_chks) { var expl = pq.pop_min_default().data; expl = Explore2Leaf(expl, p, pq); var bbf = new BBFData(expl, expl.point.Distance(p)); insert(list, k, bbf); t++; } return(list.Select(l => l.data).ToList()); }
private Move expand(MinPQ <Move> moves) { if (moves.isEmpty()) { return(null); } Move bestMove = moves.delMin(); if (bestMove.board.isGoal()) { return(bestMove); } foreach (Board neighbor in bestMove.board.neighbors()) { if (bestMove.previous == null || !neighbor.equals(bestMove.previous.board)) { moves.insert(new Move(neighbor, bestMove)); } } return(null); }
/** * Reads a sequence of transactions from standard input; takes a * command-line integer m; prints to standard output the m largest * transactions in descending order. * * @param args the command-line arguments */ public static void main(String[] args) { int m = Integer.parseInt(args[0]); MinPQ<Transaction> pq = new MinPQ<Transaction>(m+1); while (StdIn.hasNextLine()) { // Create an entry from the next line and put on the PQ. String line = StdIn.readLine(); Transaction transaction = new Transaction(line); pq.insert(transaction); // remove minimum if m+1 entries on the PQ if (pq.size() > m) pq.delMin(); } // top m entries are on the PQ // print entries on PQ in reverse order Stack<Transaction> stack = new Stack<Transaction>(); for (Transaction transaction : pq) stack.push(transaction); for (Transaction transaction : stack) StdOut.println(transaction); }
private Queue<Edge> mst = new Queue<Edge>(); // edges in MST /** * Compute a minimum spanning tree (or forest) of an edge-weighted graph. * @param G the edge-weighted graph */ public KruskalMST(EdgeWeightedGraph G) { // more efficient to build heap by passing array of edges MinPQ<Edge> pq = new MinPQ<Edge>(); for (Edge e : 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(); } } // check optimality conditions assert check(G); }