public void OnNext(long value) { // should be done with locking if (!_queue.Any()) { CurrentTick++; return; } var first = _queue.GetFirst(); while (_queue.Any() && (first.NextStateTick <= CurrentTick)) { RemoveObjectFromQueue(first); var result = first.Act(); if (!result) { AddObjectToQueue(first); } if (_queue.Any()) { first = _queue.GetFirst(); } } CurrentTick++; }
public int Solve(int k, int[] cookies) { var priorityQueue = new OrderedBag <int>(); foreach (var cookie in cookies) { priorityQueue.Add(cookie); } int currentMinSweetness = priorityQueue.GetFirst(); int steps = 0; while (currentMinSweetness < k && priorityQueue.Count > 1) { int leastSweetCookie = priorityQueue.RemoveFirst(); int secondLeastSweetCookie = priorityQueue.RemoveFirst(); int combined = leastSweetCookie + (2 * secondLeastSweetCookie); priorityQueue.Add(combined); currentMinSweetness = priorityQueue.GetFirst(); steps++; } return(currentMinSweetness < k ? -1 : steps); }
public void OnNext(long value) { // should be done with locking if (!_queue.Any()) { CurrentTick++; return; } // todo maybe write use tasks here var first = _queue.GetFirst(); while (_queue.Any() && (first.NextStateTick <= CurrentTick)) { if (first.CurrentState == null || !first.CurrentState.Eternal) { RemoveObjectFromQueue(first); first.NextState(); } /* else * { * first.NextStateTick += 1; * }*/ first = _queue.GetFirst(); } CurrentTick++; }
public T Dequeue() { var element = bag.GetFirst(); bag.RemoveFirst(); return(element); }
public int Solve(int k, int[] cookies) { OrderedBag <int> bag = new OrderedBag <int>(); foreach (var cookie in cookies) { bag.Add(cookie); } int currentMinSweetness = bag.GetFirst(); int operationsCount = 0; while (currentMinSweetness < k && bag.Count > 1) { int leastSweetCookie = bag.RemoveFirst(); int secondLeastSweetCookie = bag.RemoveFirst(); int combined = leastSweetCookie + (2 * secondLeastSweetCookie); bag.Add(combined); currentMinSweetness = bag.GetFirst(); operationsCount++; } return(currentMinSweetness < k ? -1 : operationsCount); }
public int Solve(int k, int[] cookies) { var bag = new OrderedBag <int>(); foreach (var cookie in cookies) { bag.Add(cookie); } int steps = 0; int minSweetness = bag.GetFirst(); while (minSweetness < k && bag.Count > 1) { int firstSweet = bag.RemoveFirst(); int secondSweet = bag.RemoveFirst(); int sweetness = firstSweet + (2 * secondSweet); bag.Add(sweetness); minSweetness = bag.GetFirst(); steps++; } return(minSweetness < k ? -1 : steps); }
public int Solve(int k, int[] cookies) { OrderedBag <int> orderedCookies = new OrderedBag <int>(); foreach (var cookie in cookies) { orderedCookies.Add(cookie); } int operations = 0; int currentCookie = orderedCookies.GetFirst(); while (currentCookie < k) { if (orderedCookies.Count <= 1) { return(-1); } else { currentCookie = orderedCookies.RemoveFirst() + (2 * orderedCookies.RemoveFirst()); orderedCookies.Add(currentCookie); operations++; currentCookie = orderedCookies.GetFirst(); } } return(operations); }
public int Solve(int k, int[] cookies) { var priorityQueue = new OrderedBag <int>(); foreach (var cookie in cookies) { priorityQueue.Add(cookie); } int count = 0; int currLeastSweetCookie = priorityQueue.GetFirst(); while (currLeastSweetCookie < k && priorityQueue.Count > 1) { int firstLeastSweet = priorityQueue.RemoveFirst(); int secondLeastSweet = priorityQueue.RemoveFirst(); int combined = firstLeastSweet + 2 * secondLeastSweet; priorityQueue.Add(combined); currLeastSweetCookie = priorityQueue.GetFirst(); count++; } return(currLeastSweetCookie < k ? -1 : count); }
public int Solve(int k, int[] cookies) { var bag = new OrderedBag <int>(); foreach (var cookie in cookies) { bag.Add(cookie); } var currMinSweetCookie = bag.GetFirst(); int steps = 0; while (currMinSweetCookie < k && bag.Count > 1) { var minSweetCookie = bag.RemoveFirst(); var beforeMinSweetCookie = bag.RemoveFirst(); var newCookie = minSweetCookie + (2 * beforeMinSweetCookie); bag.Add(newCookie); currMinSweetCookie = bag.GetFirst(); steps++; } return(currMinSweetCookie < k ? -1 : steps); }
private void decrease_process_level() { OrderedBag <int> fringe_top = d_fringe.Pop(); MaxTreeNode <ElementType> popped_node = pop_component_stack(); if (fringe_top.Count == 0) // if the popped fringe is empty { if (d_component_stack.Count == 0) { d_bottom_level_node = popped_node; // we are done. } else { // and add the new node to there d_component_stack.Peek().Item3.Add(popped_node); } } else // if the popped fringe is not empty { if (d_component_stack.Count == 0) { // find where tocontinue ElementType next_process_level = d_element_array[fringe_top.GetFirst()]; d_fringe.Push(fringe_top); // push the fringe back in d_component_stack.Push(new Tuple <ElementType, IList <int>, IList <MaxTreeNode <ElementType> > >(next_process_level, new List <int>(), new List <MaxTreeNode <ElementType> >())); // add the popped node as child d_component_stack.Peek().Item3.Add(popped_node); } else { ElementType fringe_level = d_element_array[fringe_top.GetFirst()]; ElementType component_stack_level = d_component_stack.Peek().Item1; if (element_value_comparer.Compare(component_stack_level, fringe_level) == -1) //TODO { d_fringe.Push(fringe_top); // push the fringe back in d_component_stack.Push(new Tuple <ElementType, IList <int>, IList <MaxTreeNode <ElementType> > >(fringe_level, new List <int>(), new List <MaxTreeNode <ElementType> >())); // add the popped node as child d_component_stack.Peek().Item3.Add(popped_node); } else { while (0 < fringe_top.Count) { d_fringe.Peek().Add(fringe_top.RemoveFirst()); } d_component_stack.Peek().Item3.Add(popped_node); } } } }
public int Solve(int k, int[] cookies) { var numOperations = 0; var bag = new OrderedBag <int>(cookies); while (bag.Count > 1) { var first = bag.RemoveFirst(); var second = 0; if (bag.Count > 0) { second = bag.RemoveFirst(); } var sum = first + (2 * second); bag.Add(sum); numOperations++; if (bag.GetFirst() >= k) { return(numOperations); } } return(-1); }
private static List <Edge> Prim(int node) { List <Edge> spanningTree = new List <Edge>(); spanningTreeNodes.Add(node); OrderedBag <Edge> prioriryQueue = new OrderedBag <Edge>(nodesByEdges[node]); while (prioriryQueue.Count > 0) { Edge edge = prioriryQueue.GetFirst(); prioriryQueue.RemoveFirst(); int nextNode = -1; if (spanningTreeNodes.Contains(edge.StartNode) && !spanningTreeNodes.Contains(edge.EndNode)) { nextNode = edge.EndNode; } if (spanningTreeNodes.Contains(edge.EndNode) && !spanningTreeNodes.Contains(edge.StartNode)) { nextNode = edge.StartNode; } if (nextNode == -1) { continue; } spanningTree.Add(edge); spanningTreeNodes.Add(nextNode); prioriryQueue.AddMany(nodesByEdges[nextNode]); } return(spanningTree); }
public IEntity PeekMostRecent() { if (Size == 0) { throw new InvalidOperationException("Operation on empty Data"); } return(data.GetFirst()); }
private void SetCutOff(DateTime value) { _cutOff = value; while (_summaries.Count > 0 && _summaries.GetFirst().Timestamp < _cutOff) { _summaries.RemoveFirst(); } }
public static void Main(string[] args) { Console.WriteLine("Please the number of paths in the network:"); int numberOfPaths = int.Parse(Console.ReadLine()); OrderedBag <Edge> edges = new OrderedBag <Edge>(); Dictionary <int, Node> nodes = new Dictionary <int, Node>(); Dictionary <int, List <Node> > parentNodes = new Dictionary <int, List <Node> >(); for (int i = 0; i < numberOfPaths; i++) { int[] pathData = ReadUserInput(); edges.Add(new Edge(pathData[0], pathData[1], pathData[2])); if (!nodes.ContainsKey(pathData[0])) { nodes[pathData[0]] = new Node(pathData[0], pathData[0]); parentNodes.Add(pathData[0], new List <Node> { nodes[pathData[0]] }); } if (!nodes.ContainsKey(pathData[1])) { nodes[pathData[1]] = new Node(pathData[1], pathData[1]); parentNodes.Add(pathData[1], new List <Node> { nodes[pathData[1]] }); } } List <NewEdge> minimalSpanningTreeEdges = new List <NewEdge>(); while (parentNodes.Count > 1) { Edge currentEdge = edges.GetFirst(); edges.RemoveFirst(); int firstNodeId = currentEdge.FirstNodeId; int secondNodeId = currentEdge.SecondNodeId; Node firstNode = nodes[firstNodeId]; Node secondNode = nodes[secondNodeId]; if (firstNode.ParentId != secondNode.ParentId) { firstNode.Neighbors.Add(secondNode); secondNode.Neighbors.Add(firstNode); SetTreeParentId(firstNode.ParentId, secondNode.ParentId, parentNodes); minimalSpanningTreeEdges.Add(new NewEdge(firstNode, secondNode, currentEdge.Distance)); } } Console.WriteLine("The resulting minimal spanning tree is:"); PrintTreeEdges(minimalSpanningTreeEdges); }
static void Main() { var strs = Console.ReadLine().Split(' '); var n = int.Parse(strs[0]); var k = int.Parse(strs[1]); if (n < k) { Console.WriteLine(0); return; } strs = Console.ReadLine().Split(' '); var f = long.Parse(strs[0]); var a = int.Parse(strs[1]); var b = int.Parse(strs[2]); var m = int.Parse(strs[3]); var set = new OrderedBag <long>(); var result = new long[k]; result[0] = (int)f; set.Add(f); for (int i = 1; i < k; ++i) { f = (f * a + b) % m; result[i] = f; set.Add(f); } for (int i = k; i < n; ++i) { f = (f * a + b) % m; var cell = set.GetFirst() + f; set.Add(cell); set.Remove(result[i % k]); result[i % k] = cell; } Console.WriteLine(set.GetFirst()); }
public static void Prim(int startNode, int damage) { var queue = new OrderedBag <Edge>(); HashSet <int> spanningTree = new HashSet <int>(); Dictionary <int, long> currentDmgs = new Dictionary <int, long>(); currentDmgs[startNode] = damage; damages[startNode] += damage; spanningTree.Add(startNode); queue.AddMany(graph[startNode]); while (queue.Count > 0) { var minEdge = queue.GetFirst(); queue.RemoveFirst(); int firstNode = minEdge.StartNode; int secondNode = minEdge.EndNode; int treeNode = -1; int nonTreeNode = -1; if (spanningTree.Contains(firstNode) && !spanningTree.Contains(secondNode)) { treeNode = firstNode; nonTreeNode = secondNode; } else if (spanningTree.Contains(secondNode) && !spanningTree.Contains(firstNode)) { treeNode = secondNode; nonTreeNode = firstNode; } else if (nonTreeNode == -1) { continue; } spanningTree.Add(nonTreeNode); if (!currentDmgs.ContainsKey(nonTreeNode)) { currentDmgs[nonTreeNode] = 0; } currentDmgs[nonTreeNode] = currentDmgs[treeNode] / 2; damages[nonTreeNode] += currentDmgs[nonTreeNode]; queue.AddMany(graph[nonTreeNode]); //if (currentDmgs[nonTreeNode] == 0) //{ // break; //} } }
static void Prim(int startingNode) { visitedNodes.Add(startingNode); var priorityQueue = new OrderedBag <Edge>(Comparer <Edge> .Create((first, second) => first.Weight - second.Weight)); //get child edges of starting node var startingNodeChildEdges = childEdges[startingNode]; //add child edges to priority queue priorityQueue.AddMany(startingNodeChildEdges); //while priority queue is not empty while (priorityQueue.Count > 0) { //get min edge by weight var minEdge = priorityQueue.GetFirst(); priorityQueue.Remove(minEdge); //check if minEdge will cause cycle //to not cause a cycle one node must be in tree, the other not var first = minEdge.FirstNode; var second = minEdge.SecondNode; var nonTreeNode = -1; if (visitedNodes.Contains(first) && !visitedNodes.Contains(second)) { nonTreeNode = second; } if (visitedNodes.Contains(second) && !visitedNodes.Contains(first)) { nonTreeNode = first; } if (nonTreeNode == -1) { continue; //both nodes are in visited -> cause cycle } //add edge to spanning tree spanningTree.Add(minEdge); //print edge Console.WriteLine($"{minEdge.FirstNode} - {minEdge.SecondNode}"); visitedNodes.Add(nonTreeNode); //enqueue all child nodes of nonTreeNode to priority queue priorityQueue.AddMany(childEdges[nonTreeNode]); } }
public int Solve(int k, int[] cookies) { var prioritySweetness = new OrderedBag <int>(); foreach (var sweetness in cookies) { prioritySweetness.Add(sweetness); } int currentCookie = prioritySweetness.GetFirst(); int operations = 0; while (currentCookie < k && prioritySweetness.Count > 1) { int firstCookie = prioritySweetness.RemoveFirst(); int secondCookie = prioritySweetness.RemoveFirst(); int combinedCookie = firstCookie + (2 * secondCookie); prioritySweetness.Add(combinedCookie); currentCookie = prioritySweetness.GetFirst(); operations++; } return(currentCookie >= k ? operations : -1); }
public int Solve(int k, int[] cookies) { var bag = new OrderedBag <int>(); foreach (var cookie in cookies) { bag.Add(cookie); } int currentCookie = bag.GetFirst(); int count = 0; while (currentCookie < k && bag.Count > 1) { int firstCookie = bag.RemoveFirst(); int secondCookie = bag.RemoveFirst(); int combined = firstCookie + 2 * secondCookie; bag.Add(combined); currentCookie = bag.GetFirst(); count++; } return(currentCookie < k ? -1 : count); }
public int Solve(int k, int[] cookies) { var priorityQueque = new OrderedBag <int>( // CompairElelemts ); foreach (var cookie in cookies) { priorityQueque.Add(cookie); } int currentMinSweetness = priorityQueque.GetFirst(); int steps = 0; while (currentMinSweetness < k && priorityQueque.Count > 1) { int leastSweetCookie = priorityQueque.RemoveFirst(); int secondLeastSweetCookie = priorityQueque.RemoveFirst(); int combined = leastSweetCookie + (2 * secondLeastSweetCookie); priorityQueque.Add(combined); currentMinSweetness = priorityQueque.GetFirst(); steps++; } return(currentMinSweetness < k ? -1 : steps); // Descending int CompairElelemts(int first, int second) { return(second - first); } //if Object implement }
public int Solve(int k, int[] cookies) { var count = 0; var bagOfCookies = new OrderedBag <int>(cookies); while (bagOfCookies.Count > 1) { if (bagOfCookies.GetFirst() > k) { return(count); } count++; var first = bagOfCookies.RemoveFirst(); var second = bagOfCookies.RemoveFirst(); bagOfCookies.Add(first + 2 * second); } if (bagOfCookies.GetFirst() > k) { return(count); } return(-1); }
protected void DFS( int k, float threshold, int node, float score, Predictions predictions, float[] hidden) { var heap = new OrderedBag <Tuple <float, int> >( predictions, new Comparison <Tuple <float, int> >((l, r) => { var b = l.Item1 > r.Item1; return(b ? 1 : 0); })); if (score < StdLog(threshold)) { return; } if (heap.Count == k && score < heap.GetFirst().Item1) { return; } if (tree_[node].left == -1 && tree_[node].right == -1) { heap.Add(Tuple.Create(score, node)); if (heap.Count > k) { heap.RemoveFirst(); } return; } var f = wo_.DotRow(hidden, node - osz_); f = 1f / (1 + (float)Math.Exp(-f)); predictions = heap.ToList(); DFS(k, threshold, tree_[node].left, score + StdLog(1f - f), predictions, hidden); DFS(k, threshold, tree_[node].right, score + StdLog(f), predictions, hidden); }
public static void PrintShortestPathLegth(Graph graph, char startNode, char goalNode) { int length = 1; OrderedBag <Edge> openEdges = new OrderedBag <Edge>(); char currentNode = startNode; bool[] visitedEdges = new bool[graph.Edges.Count]; for (int index = 0; index < graph.Edges.Count; index++) { if ((graph.Edges[index].EdgeNodeOne == currentNode) || (graph.Edges[index].EdgeNodeTwo == currentNode)) { Edge temp = graph.Edges[index]; visitedEdges[index] = true; temp.length = length; openEdges.Add(temp); } } while (openEdges.Count != 0) { Edge currentEdge = openEdges.GetFirst(); char nextNode = currentEdge.EdgeNodeTwo; openEdges.RemoveFirst(); if (currentEdge.EdgeNodeOne == goalNode || currentEdge.EdgeNodeTwo == goalNode) { Console.WriteLine(currentEdge.length); return; } length = currentEdge.length + 1; for (int index = 0; index < graph.Edges.Count; index++) { if (!visitedEdges[index]) { if ((graph.Edges[index].EdgeNodeOne == nextNode) || (graph.Edges[index].EdgeNodeTwo == nextNode)) { Edge temp = graph.Edges[index]; visitedEdges[index] = true; temp.length = length; openEdges.Add(temp); } } } } }
static void Main() { var strs = Console.ReadLine().Split(' '); var n = int.Parse(strs[0]); var m = int.Parse(strs[1]); var l = int.Parse(strs[2]); var intervals = new Tuple <int, int> [n]; for (int i = 0; i < n; ++i) { strs = Console.ReadLine().Split(' '); intervals[i] = new Tuple <int, int>( int.Parse(strs[0]), int.Parse(strs[1])); } Array.Sort(intervals); var result = 0; var boarded = new OrderedBag <int>(); foreach (var x in intervals) { while (boarded.Count > 0) { var firstItem = boarded.GetFirst(); if (firstItem > x.Item1) { break; } boarded.RemoveFirst(); ++result; } boarded.Add(x.Item2); if (boarded.Count > m) { boarded.RemoveLast(); } } result += boarded.Count; Console.WriteLine(result); }
static void Prim(int startingNode) { spanningTree.Add(startingNode); var prioriryQueue = new OrderedBag <Edge>(Comparer <Edge> .Create((f, s) => f.Weight - s.Weight)); prioriryQueue.AddMany(nodeToEdges[startingNode]); while (prioriryQueue.Count != 0) { var minEdge = prioriryQueue.GetFirst(); prioriryQueue.Remove(minEdge); var firstNode = minEdge.First; var secondNode = minEdge.Second; var nonTreeNode = -1; if (spanningTree.Contains(firstNode) && !spanningTree.Contains(secondNode)) { nonTreeNode = secondNode; } if (spanningTree.Contains(secondNode) && !spanningTree.Contains(firstNode)) { nonTreeNode = firstNode; } if (nonTreeNode == -1) { continue; } spanningTree.Add(nonTreeNode); Console.WriteLine($"{minEdge.First} - {minEdge.Second}"); prioriryQueue.AddMany(nodeToEdges[nonTreeNode]); } }
private static long GetShortestDistanceToHospital(Node hospital, Graph graph, Dictionary <int, Node> hospitals) { graph.InitGraphDijkstraDistances(); OrderedBag <Node> nextDijksrtaNode = new OrderedBag <Node>(); Set <Node> visited = new Set <Node>(); hospital.DijkstraDistance = 0; nextDijksrtaNode.Add(hospital); while (nextDijksrtaNode.Count > 0) { Node currentNode = nextDijksrtaNode.GetFirst(); nextDijksrtaNode.RemoveFirst(); visited.Add(currentNode); foreach (Connection connection in graph.NodeConnections[currentNode]) { Node targetNode = connection.TargetNode; int newDijkstraDistance = currentNode.DijkstraDistance + connection.Distance; if (newDijkstraDistance < targetNode.DijkstraDistance) { targetNode.DijkstraDistance = newDijkstraDistance; nextDijksrtaNode.Add(targetNode); } } } long totalDistanceHomes = 0; foreach (Node visitedNode in visited) { if (!hospitals.ContainsKey(visitedNode.Id)) { totalDistanceHomes += visitedNode.DijkstraDistance; } } return(totalDistanceHomes); }
private static void Prim(int startingNode) { visited.Add(startingNode); var priorityQueue = new OrderedBag <Edge>( Comparer <Edge> .Create((f, s) => f.Weight - s.Weight)); priorityQueue.AddMany(graph[startingNode]); while (priorityQueue.Any()) { var minEdge = priorityQueue.GetFirst(); priorityQueue.Remove(minEdge); // Connect a non-tree node to the spanning tree, avoiding a cycle var nonTreeNode = -1; if (visited.Contains(minEdge.Start) && !visited.Contains(minEdge.End)) { nonTreeNode = minEdge.End; } if (!visited.Contains(minEdge.Start) && visited.Contains(minEdge.End)) { nonTreeNode = minEdge.Start; } if (nonTreeNode == -1) { continue; } // Connect non-tree node & spanning tree minSpanningTree.Add(minEdge); visited.Add(nonTreeNode); priorityQueue.AddMany(graph[nonTreeNode]); } }
public static void Main() { var line = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); int n = line[0]; int m = line[1]; var orderedBag = new OrderedBag <int>(); var tickets = new Interval[n]; for (int i = 0; i < n; i++) { var passengerInfo = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); tickets[i] = new Interval(passengerInfo[0], passengerInfo[1]); } Array.Sort(tickets, (a, b) => a.Start.CompareTo(b.Start)); var selectedTickets = new OrderedBag <int>(); int result = 0; foreach (var ticket in tickets) { while (selectedTickets.Count > 0 && selectedTickets.GetFirst() <= ticket.Start) { selectedTickets.RemoveFirst(); result++; } selectedTickets.Add(ticket.End); if (selectedTickets.Count > m) { selectedTickets.RemoveLast(); } } result += selectedTickets.Count; Console.WriteLine(result); }
static void Main(string[] args) { var strs = Console.ReadLine().Split( ); var n = int.Parse(strs[0]); var m = int.Parse(strs[1]); //var l = int.Parse(strs[2]); var tickets = new Tuple <int, int> [n]; for (int i = 0; i < n; ++i) { strs = Console.ReadLine().Split( ); tickets[i] = new Tuple <int, int>( int.Parse(strs[0]), int.Parse(strs[1])); } Array.Sort(tickets); var selectedTickets = new OrderedBag <int>(); var result = n; foreach (var ticket in tickets) { while (selectedTickets.Count > 0 && selectedTickets.GetFirst() <= ticket.Item1) { selectedTickets.RemoveFirst(); } selectedTickets.Add(ticket.Item2); if (selectedTickets.Count > m) { selectedTickets.RemoveLast(); --result; } } //result += selectedTickets.Count; Console.WriteLine(result); }
/// <summary> /// AStar - Performs the A* algorithm search to find a /// solution of a given BoardNode. /// </summary> /// <param name="root">BoardNode to find a solution for</param> /// <returns>BoardNode containing the solution. NULL if no solution found</returns> public static BoardNode AStar(BoardNode root) { BoardNode current = root; Comparison<BoardNode> compare = new Comparison<BoardNode>(compareFScore); OrderedBag<BoardNode> openList = new OrderedBag<BoardNode>(compare); OrderedBag<BoardNode> closedList = new OrderedBag<BoardNode>(compare); int curGScore; int heuristic; curGScore = 0; heuristic = current.board.numRemainingLights(); current.gScore = curGScore; current.fScore = (curGScore + heuristic); openList.Add(current); while(openList.Count != 0) { current = openList.GetFirst(); if(current.clicked.Capacity >= 100000) { return null; } if(current.board.solved()) { return current; } openList.Remove(current); closedList.Add(current); addChildren(current); foreach (BoardNode child in current.children) { if (closedList.Contains(child)) { ; } else { curGScore = current.gScore + 1; if (openList.Contains(child) == false || curGScore < child.gScore) { child.gScore = (curGScore); heuristic = child.board.numRemainingLights(); child.fScore = (curGScore + heuristic); if (openList.Contains(child) == false) { openList.Add(child); } } } } } return null; }