/// <summary> /// constructor /// </summary> /// <param name="graph"></param> /// <param name="weight"></param> /// <param name="root">the node we start building the tree</param> internal MinimumSpanningTreeByPrim(BasicGraph <IEdge> graph, Func <IEdge, double> weight, int root) { this.graph = graph; this.weight = weight; this.root = root; q = new BinaryHeapPriorityQueue(graph.NodeCount); }
public void BinaryHeapPriorityQueueFunctionalityTest() { // create the queue and specify the comparison func. This is a simple lambda which returns the comparison on priorities BinaryHeapPriorityQueue <QueueElement> queue = new BinaryHeapPriorityQueue <QueueElement>((a, b) => a.Priority.CompareTo(b.Priority)); // use the generic method for all queues. PriorityQueueFunctionalityTest(queue, 100, false); }
protected override void OnSetUp() { base.OnSetUp(); _priorityQueue = new BinaryHeapPriorityQueue<int>(); for(int i = 0; i < ItemCount; i++) _priorityQueue.Enqueue(Rnd.Next(ItemCount)); }
public void BinaryHeapPriorityQueueFunctionalityTest() { // create the queue and specify the comparison func. This is a simple lambda which returns the comparison on priorities BinaryHeapPriorityQueue<QueueElement> queue = new BinaryHeapPriorityQueue<QueueElement>((a, b) => a.Priority.CompareTo(b.Priority)); // use the generic method for all queues. PriorityQueueFunctionalityTest(queue, 100, false); }
public MstLineSweeper(List <Tuple <int, int, double, double, double> > proximityEdges, Size[] nodeSizes, Point[] nodePositions) { _proximityEdges = proximityEdges; _nodeSizes = nodeSizes; _nodePositions = nodePositions; Debug.Assert(nodePositions.Length == nodeSizes.Length); _q = new BinaryHeapPriorityQueue(nodeSizes.Length * 2); }
public void Solve() { var pp = new Point(sc.Integer(), sc.Integer()); var qq = new Point(sc.Integer(), sc.Integer()); var n = sc.Integer(); var P = new Point[n + 2]; P[n] = pp; P[n + 1] = qq; var R = new int[n + 2]; for (int i = 0; i < n; i++) { P[i] = new Point(sc.Integer(), sc.Integer()); R[i] = sc.Integer(); } var dist = new double[n + 2]; for (int i = 0; i < n + 2; i++) { dist[i] = 1e18; } dist[n] = 0; var pq = new BinaryHeapPriorityQueue <KeyValuePair <int, double> >((l, r) => l.Value.CompareTo(r.Value)); pq.Enqueue(new KeyValuePair <C, double>(n, 0)); var used = new bool[n + 2]; foreach (var x in P) { Debug.WriteLine(x); } foreach (var x in R) { Debug.WriteLine(x); } while (pq.Count > 0) { var p = pq.Dequeue(); if (used[p.Key]) { continue; } Debug.WriteLine(p); used[p.Key] = true; for (int i = 0; i < n + 2; i++) { //if (used[i]) continue; var cost = get(P[i], P[p.Key], R[i] + R[p.Key]); if (dist[i] > p.Value + cost) { dist[i] = p.Value + cost; pq.Enqueue(new KeyValuePair <C, double>(i, dist[i])); } } } IO.Printer.Out.WriteLine(dist[n + 1]); }
public MstLineSweeper(List <OverlappedEdge> proximityEdges, Size[] nodeSizes, Point[] nodePositions, bool forLayers) { _proximityEdges = proximityEdges; _nodeSizes = nodeSizes; _nodePositions = nodePositions; _forLayers = forLayers; Debug.Assert(nodePositions.Length == nodeSizes.Length); _q = new BinaryHeapPriorityQueue(nodeSizes.Length * 2); }
public static string Perform(string text) { var chars = text.ToCharArray(); // Gathering alphabet frequency var alphabetFrequency = new Dictionary <char, int>(); foreach (var c in chars) // First pass through the char array { if (!alphabetFrequency.ContainsKey(c)) { alphabetFrequency.Add(c, 1); } else { alphabetFrequency[c] = alphabetFrequency[c] + 1; } } // Create binary heap var priorityQueue = new BinaryHeapPriorityQueue <TreeNode>(alphabetFrequency.Count, (i1, i2) => i2.Count.CompareTo(i1.Count)); foreach (var entry in alphabetFrequency) { var leafNode = new LeafTreeNode(entry.Value); CharToNodes.Add(entry.Key, leafNode); priorityQueue.Insert(leafNode); // Initially PQ contains only leaf nodes } // Main part of the algorithm while (priorityQueue.GetSize() > 1) { var n1 = priorityQueue.Extract(); var n2 = priorityQueue.Extract(); var innerNode = new InnerTreeNode(n1, n2); // Creates a new node with sum of frequencies... priorityQueue.Insert(innerNode); // ...and put it back } // Repeat the procedure untill PQ has only one element var root = priorityQueue.Extract(); // Take the last element (root) from the PQ root.CreateCode(alphabetFrequency.Count == 1 ? "0" : ""); // Build codes for the whole hierarchy var sb = new StringBuilder(); foreach (var t in chars) // Second pass through the char array { var c = CharToNodes[t].Code; sb.Append(c); } return(sb.ToString()); }
public static void Main() { BinaryHeapPriorityQueue<int> heap = new BinaryHeapPriorityQueue<int>(8); heap.Enqueue(new Node<int>(5, true)); heap.Enqueue(new Node<int>(1, true)); heap.Enqueue(new Node<int>(1, true)); heap.Enqueue(new Node<int>(1, true)); heap.DFS(); heap.DisplayAllValues(); }
public void GetSize_ValidParamsPassed_Success() { IPriorityQueue <int> priorityQueue = new BinaryHeapPriorityQueue <int>(5, (x, y) => - x.CompareTo(y)); priorityQueue.Insert(5); priorityQueue.Insert(4); priorityQueue.Insert(3); var size = priorityQueue.GetSize(); Assert.AreEqual(size, 3); }
// static method only public static IList <V> GetShortestPath <V, E>(IGraph <V, E> graph, V node1, V node2, bool directionSensitive) { if (node1.Equals(node2)) { return(Java.Util.Collections.SingletonList(node2)); } ICollection <V> visited = Generics.NewHashSet(); IDictionary <V, V> previous = Generics.NewHashMap(); BinaryHeapPriorityQueue <V> unsettledNodes = new BinaryHeapPriorityQueue <V>(); unsettledNodes.Add(node1, 0); while (unsettledNodes.Count > 0) { double distance = unsettledNodes.GetPriority(); V u = unsettledNodes.RemoveFirst(); visited.Add(u); if (u.Equals(node2)) { break; } unsettledNodes.Remove(u); ICollection <V> candidates = ((directionSensitive) ? graph.GetChildren(u) : graph.GetNeighbors(u)); foreach (V candidate in candidates) { double alt = distance - 1; // nodes not already present will have a priority of -inf if (alt > unsettledNodes.GetPriority(candidate) && !visited.Contains(candidate)) { unsettledNodes.RelaxPriority(candidate, alt); previous[candidate] = u; } } } if (!previous.Contains(node2)) { return(null); } List <V> path = new List <V>(); path.Add(node2); V n = node2; while (previous.Contains(n)) { path.Add(previous[n]); n = previous[n]; } Java.Util.Collections.Reverse(path); return(path); }
public void Peek_ValidParamsPassed_Success() { IPriorityQueue <int> priorityQueue = new BinaryHeapPriorityQueue <int>(5, (x, y) => - x.CompareTo(y)); priorityQueue.Insert(5); priorityQueue.Insert(4); priorityQueue.Insert(3); priorityQueue.Insert(2); priorityQueue.Insert(1); var v1 = priorityQueue.Peek(); Assert.AreEqual(v1, 1); }
public void Insert_QueueOverflow_Failure() { IPriorityQueue <int> priorityQueue = new BinaryHeapPriorityQueue <int>(4, (x, y) => y.CompareTo(x)); priorityQueue.Insert(5); priorityQueue.Insert(4); priorityQueue.Insert(3); priorityQueue.Insert(2); Assert.Throws <InvalidOperationException>(() => { priorityQueue.Insert(1); }); }
public static void Main(string[] args) { IPriorityQueue <string> q = new BinaryHeapPriorityQueue <string>(); q.Add("bla", 2); q.Add("bla3", 2); logger.Info("size of q " + q.Count); Edu.Stanford.Nlp.Classify.PRCurve pr = new Edu.Stanford.Nlp.Classify.PRCurve("c:/data0204/precsvm", true); logger.Info("acc " + pr.Accuracy() + " opt " + pr.OptimalAccuracy() + " cwa " + pr.Cwa() + " optcwa " + pr.OptimalCwa()); for (int r = 1; r <= pr.NumSamples(); r++) { logger.Info("optimal precision at recall " + r + " " + pr.Precision(r)); logger.Info("model precision at recall " + r + " " + pr.LogPrecision(r)); } }
public void Insert_ValidParamsPassed_Success() { IPriorityQueue <int> priorityQueue = new BinaryHeapPriorityQueue <int>(10, (x, y) => y.CompareTo(x)); priorityQueue.Insert(10); priorityQueue.Insert(9); priorityQueue.Insert(8); priorityQueue.Insert(7); priorityQueue.Insert(6); priorityQueue.Insert(5); priorityQueue.Insert(4); priorityQueue.Insert(3); priorityQueue.Insert(2); priorityQueue.Insert(1); Assert.IsTrue(priorityQueue.IsFull()); }
public virtual void InitMC <F>(IProbabilisticClassifier <L, F> classifier, GeneralDataset <L, F> data) { //if (!(gData instanceof Dataset)) { // throw new UnsupportedOperationException("Can only handle Datasets, not "+gData.getClass().getName()); //} // //Dataset data = (Dataset)gData; IPriorityQueue <Pair <int, Pair <double, bool> > > q = new BinaryHeapPriorityQueue <Pair <int, Pair <double, bool> > >(); total = 0; correct = 0; logLikelihood = 0.0; for (int i = 0; i < data.Size(); i++) { IDatum <L, F> d = data.GetRVFDatum(i); ICounter <L> scores = classifier.LogProbabilityOf(d); L guess = Counters.Argmax(scores); L correctLab = d.Label(); double guessScore = scores.GetCount(guess); double correctScore = scores.GetCount(correctLab); int guessInd = data.LabelIndex().IndexOf(guess); int correctInd = data.LabelIndex().IndexOf(correctLab); total++; if (guessInd == correctInd) { correct++; } logLikelihood += correctScore; q.Add(new Pair <int, Pair <double, bool> >(int.Parse(i), new Pair <double, bool>(guessScore, bool.ValueOf(guessInd == correctInd))), -guessScore); } accuracy = (double)correct / (double)total; IList <Pair <int, Pair <double, bool> > > sorted = q.ToSortedList(); scores = new double[sorted.Count]; isCorrect = new bool[sorted.Count]; for (int i_1 = 0; i_1 < sorted.Count; i_1++) { Pair <double, bool> next = sorted[i_1].Second(); scores[i_1] = next.First(); isCorrect[i_1] = next.Second(); } }
public virtual void Init(IList <Pair <double, int> > dataScores) { IPriorityQueue <Pair <int, Pair <double, int> > > q = new BinaryHeapPriorityQueue <Pair <int, Pair <double, int> > >(); for (int i = 0; i < dataScores.Count; i++) { q.Add(new Pair <int, Pair <double, int> >(int.Parse(i), dataScores[i]), -dataScores[i].First()); } IList <Pair <int, Pair <double, int> > > sorted = q.ToSortedList(); scores = new double[sorted.Count]; classes = new int[sorted.Count]; logger.Info("incoming size " + dataScores.Count + " resulting " + sorted.Count); for (int i_1 = 0; i_1 < sorted.Count; i_1++) { Pair <double, int> next = sorted[i_1].Second(); scores[i_1] = next.First(); classes[i_1] = next.Second(); } Init(); }
public void Extract_ValidParamsPassed_Success() { IPriorityQueue <int> priorityQueue = new BinaryHeapPriorityQueue <int>(5, (x, y) => - x.CompareTo(y)); priorityQueue.Insert(5); priorityQueue.Insert(4); priorityQueue.Insert(3); priorityQueue.Insert(2); priorityQueue.Insert(1); var v1 = priorityQueue.Extract(); var v2 = priorityQueue.Extract(); var v3 = priorityQueue.Extract(); var v4 = priorityQueue.Extract(); var v5 = priorityQueue.Extract(); Assert.AreEqual(v1, 1); Assert.AreEqual(v2, 2); Assert.AreEqual(v3, 3); Assert.AreEqual(v4, 4); Assert.AreEqual(v5, 5); }
public void Extract_StringDataType_Success() { IPriorityQueue <string> priorityQueue = new BinaryHeapPriorityQueue <string>(10, (x, y) => - string.Compare(x, y, StringComparison.Ordinal)); priorityQueue.Insert("Z"); priorityQueue.Insert("X"); priorityQueue.Insert("Y"); priorityQueue.Insert("W"); priorityQueue.Insert("V"); priorityQueue.Insert("U"); priorityQueue.Insert("T"); priorityQueue.Insert("S"); priorityQueue.Insert("R"); priorityQueue.Insert("Q"); var v1 = priorityQueue.Extract(); var v2 = priorityQueue.Extract(); var v3 = priorityQueue.Extract(); var v4 = priorityQueue.Extract(); var v5 = priorityQueue.Extract(); var v6 = priorityQueue.Extract(); var v7 = priorityQueue.Extract(); var v8 = priorityQueue.Extract(); var v9 = priorityQueue.Extract(); var v10 = priorityQueue.Extract(); Assert.AreEqual(v1, "Q"); Assert.AreEqual(v2, "R"); Assert.AreEqual(v3, "S"); Assert.AreEqual(v4, "T"); Assert.AreEqual(v5, "U"); Assert.AreEqual(v6, "V"); Assert.AreEqual(v7, "W"); Assert.AreEqual(v8, "X"); Assert.AreEqual(v9, "Y"); Assert.AreEqual(v10, "Z"); }
public void Extract_StringDataTypeDifferentOrder_Success() { IPriorityQueue <string> priorityQueue = new BinaryHeapPriorityQueue <string>(10, (x, y) => string.Compare(x, y, StringComparison.Ordinal)); priorityQueue.Insert("A"); priorityQueue.Insert("B"); priorityQueue.Insert("C"); priorityQueue.Insert("D"); priorityQueue.Insert("E"); priorityQueue.Insert("F"); priorityQueue.Insert("G"); priorityQueue.Insert("H"); priorityQueue.Insert("I"); priorityQueue.Insert("J"); var v1 = priorityQueue.Extract(); var v2 = priorityQueue.Extract(); var v3 = priorityQueue.Extract(); var v4 = priorityQueue.Extract(); var v5 = priorityQueue.Extract(); var v6 = priorityQueue.Extract(); var v7 = priorityQueue.Extract(); var v8 = priorityQueue.Extract(); var v9 = priorityQueue.Extract(); var v10 = priorityQueue.Extract(); Assert.AreEqual(v1, "J"); Assert.AreEqual(v2, "I"); Assert.AreEqual(v3, "H"); Assert.AreEqual(v4, "G"); Assert.AreEqual(v5, "F"); Assert.AreEqual(v6, "E"); Assert.AreEqual(v7, "D"); Assert.AreEqual(v8, "C"); Assert.AreEqual(v9, "B"); Assert.AreEqual(v10, "A"); }
public static /*<V, E>*/ List <V> GetShortestPath <V, E>(IGraph <V, E> graph, V node1, V node2, bool directionSensitive) { if (node1.Equals(node2)) { //return Collections.singletonList(node2); return(new List <V>() { node2 }); } Set <V> visited = new Util.HashSet <V>(); var previous = new Dictionary <V, V>(); var unsettledNodes = new BinaryHeapPriorityQueue <V>(); unsettledNodes.Add(node1, 0); while (unsettledNodes.Size() > 0) { var distance = unsettledNodes.GetPriority(); var u = unsettledNodes.RemoveFirst(); visited.Add(u); if (u.Equals(node2)) { break; } unsettledNodes.Remove(u); var candidates = ((directionSensitive) ? graph.GetChildren(u) : new ReadOnlyCollection <V>(graph.GetNeighbors(u))); foreach (var candidate in candidates) { var alt = distance - 1; // nodes not already present will have a priority of -inf if (alt > unsettledNodes.GetPriority(candidate) && !visited.Contains(candidate)) { unsettledNodes.RelaxPriority(candidate, alt); previous[candidate] = u; } } } if (!previous.ContainsKey(node2)) { return(null); } var path = new List <V> { node2 }; var n = node2; while (previous.ContainsKey(n)) { path.Add(previous[n]); n = previous[n]; } path.Reverse(); return(path); }
public void IsEmpty_ValidParamsPassed_Success() { IPriorityQueue <int> priorityQueue = new BinaryHeapPriorityQueue <int>(5, (x, y) => x.CompareTo(y)); Assert.IsTrue(priorityQueue.IsEmpty()); }
public void MSAGLAstarSSSP(Vertex[] vList, Edge[,] eList, int[] degList, int source, Dictionary <Node, int> nodeId, GeometryGraph _mainGeometryGraph, int NofNodesBeforeDetour, int n, Tiling g, Tiling g1) { var q = new BinaryHeapPriorityQueue(n); vList[source].Dist = 0; q.Enqueue(source, vList[source].Dist); for (int i = 0; i < n; i++) { if (vList[i].Id != source) { vList[i].Dist = double.MaxValue; q.Enqueue(i, vList[i].Dist); } vList[i].Parent = null; vList[i].Visited = false; } Distance = 0; while (q.Count > 0) { var deq = q.Dequeue(); Vertex u = vList[deq]; u.Visited = true; if (u == null || u.Invalid) { return; } for (int neighb = 0; neighb < degList[u.Id]; neighb++) { var neighborId = eList[u.Id, neighb].NodeId; int discourage = 0; if (u.Id < NofNodesBeforeDetour && u.Id != source) { discourage = 1000; } Vertex neighbor = vList[neighborId]; double edist = MsaglUtilities.EucledianDistance(u.XLoc, u.YLoc, neighbor.XLoc, neighbor.YLoc); var tempDist = u.Dist + edist + discourage; if (tempDist >= neighbor.Dist) { continue; } neighbor.Dist = tempDist; neighbor.Parent = u; if (neighbor.Visited) { neighbor.Visited = false; q.Enqueue(neighbor.Id, neighbor.Dist); } else { q.DecreasePriority(neighbor.Id, neighbor.Dist); } } } foreach (var node in _mainGeometryGraph.Nodes) { int target = nodeId[node]; if (target == source) { continue; } Vertex route = vList[target]; int zoomlevel = Math.Max(vList[source].ZoomLevel, vList[target].ZoomLevel); Edgelist.Clear(); while (route.Parent != null) { ShortestPath.Add(route.Id); for (int neighb = 0; neighb < degList[route.Id]; neighb++) { if (eList[route.Id, neighb].NodeId == route.Parent.Id) { SetUsed(vList, eList, degList, route.Id, eList[route.Id, neighb].NodeId, zoomlevel); Edgelist.Add(new VertexNeighbor(route.Id, neighb)); break; } } route = route.Parent; } if (route.Id != source) { Debug.WriteLine("path not found"); } foreach (VertexNeighbor vn in Edgelist) { g1.AddEdge(vn.A, g.EList[vn.A, vn.Neighbor].NodeId, g.EList[vn.A, vn.Neighbor].Selected, g.EList[vn.A, vn.Neighbor].Used); } } return; }
public void Solve() { var n = sc.Integer(); var q = sc.Integer(); var a = new List <long>() { n }; for (int i = 0; i < q; i++) { a.Add(sc.Long()); } a.Reverse(); var A = new BinaryHeapPriorityQueue(); var last = -1L; foreach (var x in a) { if (A.Count == 0) { A.Enqueue(new KeyValuePair <Number, Number>(x, 1)); } else { if (last <= x) { continue; } while (A.Any()) { if (A.Peek().Key <= x) { break; } var y = A.Dequeue(); var l = y.Key; var v = y.Value; if (A.Any() && A.Peek().Key == l) { var z = A.Dequeue(); v += z.Value; } var k = l / x; A.Enqueue(new KeyValuePair <Number, Number>(x, k * v)); if (l % x != 0) { A.Enqueue(new KeyValuePair <Number, Number>(l % x, v)); } } } last = x; } var ans = new long[n + 1]; while (A.Any()) { var p = A.Dequeue(); ans[p.Key] += p.Value; } for (int i = n - 1; i >= 0; i--) { ans[i] += ans[i + 1]; } for (int i = 0; i < n; i++) { IO.Printer.Out.WriteLine(ans[i + 1]); } }
public List <int> MSAGLAstarShortestPath(Vertex[] vList, Edge[,] eList, int[] degList, int source, int target, int n) { var q = new BinaryHeapPriorityQueue(n); vList[source].Dist = 0; vList[source].Weight = vList[source].Dist + MsaglUtilities.EucledianDistance( vList[source].XLoc, vList[source].YLoc, vList[target].XLoc, vList[target].YLoc); q.Enqueue(source, vList[source].Weight); for (int i = 0; i < n; i++) { if (vList[i].Id != source) { vList[i].Dist = double.MaxValue; vList[i].Weight = double.MaxValue; q.Enqueue(i, vList[i].Weight); } vList[i].Parent = null; vList[i].Visited = false; } Edgelist.Clear(); ShortestPath.Clear(); Distance = 0; while (q.Count > 0) { var deq = q.Dequeue(); Vertex u = vList[deq]; u.Visited = true; if (u == null || u.Invalid) { return(new List <int>()); } for (int neighb = 0; neighb < degList[u.Id]; neighb++) { var neighborId = eList[u.Id, neighb].NodeId; int discourage = 0; if (eList[u.Id, neighb].Selected == 1) { discourage = 1000; //continue; } if (eList[u.Id, neighb].NodeId == source || eList[u.Id, neighb].NodeId == target) { discourage = 0; } if (u.Id == source || u.Id == target) { discourage = 0; } Vertex neighbor = vList[neighborId]; double edist = MsaglUtilities.EucledianDistance(u.XLoc, u.YLoc, neighbor.XLoc, neighbor.YLoc); var tempDist = u.Dist + edist + discourage; if (tempDist >= neighbor.Dist) { continue; } neighbor.Dist = tempDist; var tempWeight = neighbor.Dist + MsaglUtilities.EucledianDistance(vList[target].XLoc, vList[target].YLoc, neighbor.XLoc, neighbor.YLoc); neighbor.Weight = tempWeight; neighbor.Parent = u; if (neighbor.Visited) { neighbor.Visited = false; q.Enqueue(neighbor.Id, neighbor.Weight); } else { q.DecreasePriority(neighbor.Id, neighbor.Weight); } } if (u.Id == target) { break; } } Vertex route = vList[target]; int zoomlevel = Math.Max(vList[source].ZoomLevel, vList[target].ZoomLevel); while (route.Parent != null) { ShortestPath.Add(route.Id); for (int neighb = 0; neighb < degList[route.Id]; neighb++) { if (eList[route.Id, neighb].NodeId == route.Parent.Id) { SetUsed(vList, eList, degList, route.Id, eList[route.Id, neighb].NodeId, zoomlevel); Edgelist.Add(new VertexNeighbor(route.Id, neighb)); Distance += Math.Sqrt((route.XLoc - route.Parent.XLoc) * (route.XLoc - route.Parent.XLoc) + (route.YLoc - route.Parent.YLoc) * (route.YLoc - route.Parent.YLoc)); break; } } route = route.Parent; } ShortestPath.Add(route.Id); if (route.Id != source) { Debug.WriteLine("path not found"); } return(ShortestPath); }