public int minMeetingRooms(Interval[] intervals) { if (intervals == null || intervals.length == 0) return 0; Arrays.sort( intervals, new Comparator<Interval>() { public int compare(Interval a, Interval b) { return a.start - b.start; } }); PriorityQueue<Interval> heap = new PriorityQueue<Interval>( intervals.length, new Comparator<Interval>() { public int compare(Interval a, Interval b) { return a.end - b.end; } }); heap.offer(intervals[0]); for (int i = 1; i < intervals.length; i++) { Interval poll = heap.poll(); if (intervals[i].start >= poll.end) poll.end = intervals[i].end; else heap.offer(intervals[i]); heap.offer(poll); } return heap.size(); }
public static SearchResult generic(SearchProblem prob, Comparator<SearchNode> cmp) { PriorityQueue<SearchNode> frontier = new PriorityQueue<SearchNode>(10000, cmp); frontier.offer(prob.startNode()); Set<State> explored = new HashSet<State>(); while (!frontier.isEmpty()) { SearchNode candidate = frontier.poll(); if (candidate.isGoal()) { return new SearchResult(candidate, explored.size(), frontier.size()); } List<Action> nextActions = prob.actions(candidate.state); for (Action action : nextActions) { SearchNode child = prob.childNode(candidate, action); if (!explored.contains(child.state)) { frontier.offer(child); explored.add(candidate.state); } } } return null; }
public List<Task> mockRunTaks(List<Task> tasks) { PriorityQueue<Task> taskQueue = new PriorityQueue<Task>( new Comparator<Task>() { @Override public int compare(Task t1, Task t2) { return t1.priority - t2.priority; } }); List<Task> runOrder = new ArrayList<Task>(); HashMap<Task, Integer> taskIndegrees = new HashMap<Task, Integer>(); for (Task task : tasks) { taskIndegrees.put(task, task.dependencies.size()); if (task.dependencies.size() == 0) { taskQueue.offer(task); } } while (!taskQueue.isEmpty()) { Task curTask = taskQueue.poll(); runOrder.add(curTask); for (Task task : curTask.dependencies) { taskIndegrees.put(task, taskIndegrees.get(task) - 1); if (taskIndegrees.get(task) == 0) taskQueue.offer(task); } } return runOrder; }
// Adds a number into the data structure. public void addNum(int num) { minHeap.offer(num); if (minHeap.size() - maxHeap.size() > 1) { maxHeap.offer(minHeap.poll()); } }
/** * initial for routing, if the start node is an intersect, then it should already in the adjlist, * than we just add it. If the start node is not intersect, then the node will not in adjlist, we * need find the node's two edge entrance if the edge is bidirection or one edge entrance if the * edge is oneway. * * @param startNode * @param endNode * @param startTime * @param dayIndex * @param nodeHelperCache */ public static PriorityQueue<NodeInfoHelper> initialStartSet( long startNode, long endNode, int startTime, int dayIndex, HashMap<Long, NodeInfoHelper> nodeHelperCache) { PriorityQueue<NodeInfoHelper> openSet = new PriorityQueue<NodeInfoHelper>( 10000, new Comparator<NodeInfoHelper>() { public int compare(NodeInfoHelper n1, NodeInfoHelper n2) { return (int) (n1.getTotalCost() - n2.getTotalCost()); } }); NodeInfo start = OSMData.nodeHashMap.get(startNode); NodeInfoHelper current; // initial start end set if (start.isIntersect()) { // initial current = new NodeInfoHelper(startNode); current.setCost(0); current.setCurrentLevel(10); current.setHeuristic(OSMRouting.estimateHeuristic(startNode, endNode)); openSet.offer(current); // push the start node nodeHelperCache.put(current.getNodeId(), current); // add cache } else { EdgeInfo edge = start.getOnEdgeList().getFirst(); double travelTime = 1; // second int distance; // feet int totalDistance = edge.getDistance(); // feet if (!edge.isOneway()) { // distance from start to middle distance = edge.getStartDistance(startNode); travelTime = edge.getTravelTime(startTime, dayIndex, false); travelTime *= (double) distance / totalDistance; travelTime /= OSMParam.MILLI_PER_SECOND; current = new NodeInfoHelper(edge.getStartNode()); current.setCost(travelTime); current.setCurrentLevel(10); current.setHeuristic(OSMRouting.estimateHeuristic(edge.getStartNode(), endNode)); openSet.offer(current); // push the start node nodeHelperCache.put(current.getNodeId(), current); // add cache } // distance from middle to end distance = edge.getEndDistance(startNode); travelTime = edge.getTravelTime(startTime, dayIndex, true); travelTime *= (double) distance / totalDistance; current = new NodeInfoHelper(edge.getEndNode()); current.setCost(travelTime); current.setCurrentLevel(10); current.setHeuristic(OSMRouting.estimateHeuristic(edge.getEndNode(), endNode)); openSet.offer(current); // push the start node nodeHelperCache.put(current.getNodeId(), current); // add cache } return openSet; }
public static void main(String[] args) { PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); pq.offer(6); pq.offer(-3); pq.offer(9); pq.offer(0); System.out.println(pq); while (pq.peek() != null) { System.out.print(pq.poll() + ", "); } System.out.println(); }
public static void main(String[] args) { PriorityQueue pq = new PriorityQueue(); // 下面代码依次向pq中加入四个元素 pq.offer(6); pq.offer(-3); pq.offer(9); pq.offer(0); // 输出pq队列,并不是按元素的加入顺序排列,而是按元素的大小顺序排列 System.out.println(pq); // 访问队列第一个元素,其实就是队列中最小的元素:-3 System.out.println(pq.peek()); }
static void sweep(ArrayList<Integer> indexes) { PriorityQueue<Event> pq = new PriorityQueue<Event>(); for (int i = 0; i < indexes.size(); i++) { pq.offer(new Event(lo[val[indexes.get(i)]] + 1, 1, indexes.get(i))); pq.offer(new Event(hi[val[indexes.get(i)]], -1, indexes.get(i))); } TreeSet<Integer> active = new TreeSet<Integer>(); while (!pq.isEmpty()) { Event curr = pq.poll(); if (curr.type == 1) active.add(curr.index); else if (curr.type == -1) { active.remove(curr.index); Integer lower = active.lower(curr.index); if (lower != null && lower > lo[val[curr.index]]) { Interval add = new Interval(lower, curr.index); Interval prev = intervals.floor(add); Interval next = intervals.ceiling(add); boolean intersectPrev = true; boolean intersectNext = true; if (prev != null) { if (Math.max(add.l, prev.l) < Math.min(add.r, prev.r)) { if (add.r - add.l <= prev.r - prev.l) { intervals.remove(prev); intersectPrev = false; } } else { intersectPrev = false; } } else { intersectPrev = false; } if (next != null) { if (Math.max(add.l, next.l) < Math.min(add.r, next.r)) { if (add.r - add.l <= next.r - next.l) { intervals.remove(next); intersectNext = false; } } else { intersectNext = false; } } else { intersectNext = false; } if (!intersectPrev && !intersectNext) intervals.add(add); } } } }
public ListNode mergeKLists(List<ListNode> lists) { PriorityQueue<Integer> pq = new PriorityQueue<Integer>(1024); List<ListNode> ps = new ArrayList<>(); ListNode root = new ListNode(0); ListNode cur = root; boolean nothingNew = false; for (ListNode list : lists) ps.add(list); while (true) { nothingNew = true; for (int i = 0; i < ps.size(); i++) { ListNode list = ps.get(i); if (list != null) { nothingNew = false; pq.offer(list.val); ps.set(i, list.next); } } if (nothingNew) break; cur.next = new ListNode(pq.poll()); cur = cur.next; } while (pq.size() > 0) { cur.next = new ListNode(pq.poll()); cur = cur.next; } return root.next; }
public void adjustTellerNumber() { // This is actually a control system. By adjusting // the numbers, you can reveal stability issues in // the control mechanism. // If line is too long, add another teller: if (customers.size() / workingTellers.size() > 2) { // If tellers are on break or doing // another job, bring one back: if (tellersDoingOtherThings.size() > 0) { Teller teller = tellersDoingOtherThings.remove(); teller.serveCustomerLine(); workingTellers.offer(teller); return; } // Else create (hire) a new teller Teller teller = new Teller(customers); exec.execute(teller); workingTellers.add(teller); return; } // If line is short enough, remove a teller: if (workingTellers.size() > 1 && customers.size() / workingTellers.size() < 2) reassignOneTeller(); // If there is no line, we only need one teller: if (customers.size() == 0) while (workingTellers.size() > 1) reassignOneTeller(); }
/** * using low bound for travel time, for reverse searching * * @param endNode * @param startNode * @param openSet * @param nodeHelperCache */ public void initialEndSet( long startNode, long endNode, PriorityQueue<NodeInfoHelper> openSet, HashMap<Long, NodeInfoHelper> nodeHelperCache) { NodeInfo start = OSMData.nodeHashMap.get(startNode); NodeInfoHelper current; // initial start end set if (start.isIntersect()) { // initial current = new NodeInfoHelper(startNode); current.setCost(0); current.setCurrentLevel(10); current.setHeuristic(OSMRouting.estimateHeuristic(startNode, endNode)); openSet.offer(current); // push the start node nodeHelperCache.put(current.getNodeId(), current); // add cache } else { EdgeInfo edge = start.getOnEdgeList().getFirst(); double travelTime = 1; // second int distance; // feet int totalDistance = edge.getDistance(); // feet if (!edge.isOneway()) { // distance from start to middle distance = edge.getStartDistance(startNode); // get low bound of travel time travelTime = edge.getTravelTimeMin(false); travelTime *= (double) distance / totalDistance; current = new NodeInfoHelper(edge.getStartNode()); current.setCost(travelTime); current.setCurrentLevel(10); current.setHeuristic(OSMRouting.estimateHeuristic(edge.getStartNode(), endNode)); openSet.offer(current); // push the start node nodeHelperCache.put(current.getNodeId(), current); // add cache } // distance from middle to end distance = edge.getEndDistance(startNode); travelTime = edge.getTravelTimeMin(true); travelTime *= (double) distance / totalDistance; current = new NodeInfoHelper(edge.getEndNode()); current.setCost(travelTime); current.setCurrentLevel(10); current.setHeuristic(OSMRouting.estimateHeuristic(edge.getEndNode(), endNode)); openSet.offer(current); // push the start node nodeHelperCache.put(current.getNodeId(), current); // add cache } }
/** * Inserts the specified element into this delay queue. * * @param e the element to add * @return <tt>true</tt> * @throws NullPointerException if the specified element is null */ public boolean offer(E e) { final ReentrantLock lock = this.lock; lock.lock(); try { E first = q.peek(); q.offer(e); if (first == null || e.compareTo(first) < 0) available.signalAll(); return true; } finally { lock.unlock(); } }
static void solve(Scanner sc) throws IOException { int h = sc.nextInt(); int w = sc.nextInt(); int k = sc.nextInt(); PriorityQueue<Node> pq = new PriorityQueue<Node>(); for (int i = 0; i < h; i++) { String s = sc.next(); for (int j = 0; j < w; j++) { grid[i][j] = s.charAt(j); dis[i][j] = grid[i][j] == '#' ? 0 : inf; if (grid[i][j] == 'S') pq.offer(new Node(i, j, 0)); } } // Dijkstra // There is always a solution according to problem statement while (!pq.isEmpty()) { Node z = pq.poll(); int x = z.x; int y = z.y; int d = z.dis; if (d > dis[x][y]) continue; if (x == 0 || x == h - 1 || y == 0 || y == w - 1) { System.out.println(d + 1); break; } for (int i = 0; i < 4; i++) { int nx = x + dx[i]; int ny = y + dy[i]; // if(nx<0||nx>=h||ny<0||ny>=w) // continue; int nd = d + 1 + (grid[nx][ny] == '@' ? k : 0); if (nd < dis[nx][ny]) { dis[nx][ny] = nd; pq.offer(new Node(nx, ny, nd)); } } } }
public ListNode mergeKLists(ListNode[] lists) { if (lists == null || lists.length == 0) return null; int k = lists.length; PriorityQueue<ListNode> pq = new PriorityQueue<ListNode>( lists.length, new Comparator<ListNode>() { @Override public int compare(ListNode o1, ListNode o2) { if (o1.val < o2.val) { return -1; } else if (o1.val == o2.val) { return 0; } else { return 1; } } }); for (int i = 0; i < k; i++) { if (lists[i] != null) { pq.offer(lists[i]); } } ListNode tmp = new ListNode(0); ListNode cur = tmp; while (!pq.isEmpty()) { cur.next = pq.poll(); // very important here. Don't create new Node. Just point to the orignial // one. otherwise you loose the link. cur = cur.next; if (cur.next != null) { pq.offer(cur.next); } } return tmp.next; }
/** * Inserts the specified element into this delay queue. * * @param e the element to add * @return <tt>true</tt> * @throws NullPointerException if the specified element is null */ public boolean offer(E e) { final ReentrantLock lock = this.lock; lock.lock(); try { q.offer(e); if (q.peek() == e) { leader = null; available.signal(); } return true; } finally { lock.unlock(); } }
// 保存待访问的URL及其优先级 private static void SavePriorQueue(String filepath) throws Exception { BufferedWriter bw = new BufferedWriter(new FileWriter(filepath)); PriorityQueue<UrlValue> temp = new PriorityQueue<UrlValue>(); UrlValue cur = null; while (pq.peek() != null) { cur = pq.remove(); temp.offer(cur); bw.write(cur.url + " " + cur.value); bw.newLine(); } pq = temp; bw.flush(); bw.close(); }
// You can add extra function if needed // -------------------------------------------- int dijkstra() { IntegerPair current; while (!q.isEmpty()) { current = q.poll(); if (weights.get(current.first()) == current.second()) for (IntegerPair next : AdjList.get(current.first())) { if (weights.get(next.first()) > current.second() + next.second()) { weights.set(next.first(), current.second() + next.second()); q.offer(new IntegerPair(next.first(), weights.get(next.first()))); } } } return weights.get(1); }
int Query() { // You have to report the shortest path from Steven and Grace's home (vertex 0) // to reach their chosen hospital (vertex 1) // // write your answer here q = new PriorityQueue<IntegerPair>(); weights = new Vector<Integer>(); weights.setSize(V); Collections.fill(weights, Integer.MAX_VALUE); // initially all infinite q.offer(new IntegerPair(0, 0)); weights.set(0, 0); return dijkstra(); }
public static void main(String[] args) { PriorityQueue<Integer> priorityQueue = new PriorityQueue<Integer>(); Random rand = new Random(47); for (int i = 0; i < 10; i++) { priorityQueue.offer(rand.nextInt(i + 10)); } QueueDemo.printQueue(priorityQueue); List<Integer> ints = Arrays.asList(25, 22, 20, 18, 14, 9, 3, 1, 1, 2, 3, 9, 14, 18, 21, 23, 25); priorityQueue = new PriorityQueue<Integer>(ints); QueueDemo.printQueue(priorityQueue); priorityQueue = new PriorityQueue<Integer>(ints.size(), Collections.reverseOrder()); priorityQueue.addAll(ints); QueueDemo.printQueue(priorityQueue); String fact = "EDUCATION SHOULD ESCHEW OBFUSCATION"; List<String> strings = Arrays.asList(fact.split("")); PriorityQueue<String> stringPQ = new PriorityQueue<String>(strings); QueueDemo.printQueue(stringPQ); }
// 加载待访问的url private static void SetPriorQueue(String filePath) throws Exception { BufferedReader br = new BufferedReader(new FileReader(filePath)); Scanner sc = null; String line = null; String url = null; UrlValue cur = null; while ((line = br.readLine()) != null) { line = line.trim(); if (!line.equals("")) { sc = new Scanner(line); url = sc.next(); if (!visitedUrl.contains(url)) { cur = new UrlValue(); cur.url = url; cur.value = sc.nextDouble(); pq.offer(cur); } } } br.close(); }
// 清除所有优先队列的数据,设置优先种子 private static void SetSeeds(String filepath) throws Exception { pq.clear(); BufferedReader br = new BufferedReader(new FileReader(filepath)); String line = null; UrlValue cur = null; visitedPrint(); while ((line = br.readLine()) != null) { line = line.trim(); // System.out.println(line); if (!line.equals("")) { if (!visitedUrl.contains(line)) { cur = new UrlValue(); cur.url = line; cur.value = 1; pq.offer(cur); } else { System.out.println("contain"); } } } br.close(); }
public static void main(String[] args) throws Exception { int V, E, s, u, v, w; /* // Graph in Figure 4.17 5 7 2 2 1 2 2 3 7 2 0 6 1 3 3 1 4 6 3 4 5 0 4 1 */ Scanner sc = new Scanner(System.in); V = sc.nextInt(); E = sc.nextInt(); s = sc.nextInt(); AdjList.clear(); for (int i = 0; i < V; i++) { ArrayList<IntegerPair> Neighbor = new ArrayList<IntegerPair>(); AdjList.add(Neighbor); // add neighbor list to Adjacency List } for (int i = 0; i < E; i++) { u = sc.nextInt(); v = sc.nextInt(); w = sc.nextInt(); AdjList.get(u).add(new IntegerPair(v, w)); // first time using weight } // Dijkstra routine ArrayList<Integer> dist = new ArrayList<>(); // INF = 1*10^9 not MAX_INT to avoid overflow dist.addAll(Collections.nCopies(V, INF)); dist.set(s, 0); PriorityQueue<IntegerPair> pq = new PriorityQueue<IntegerPair>( 1, new Comparator<IntegerPair>() { // overriding the compare method public int compare(IntegerPair i, IntegerPair j) { return i.dfs - j.dfs; } }); pq.offer(new IntegerPair(s, 0)); // sort based on increasing distance while (!pq.isEmpty()) { // main loop IntegerPair top = pq.poll(); // greedy: pick shortest unvisited vertex int d = top.dfs; u = top.vn; if (d > dist.get(u)) continue; // We want to process vertex u only once! Iterator it = AdjList.get(u).iterator(); while (it.hasNext()) { // all outgoing edges from u IntegerPair p = (IntegerPair) it.next(); v = p.vn; int weight_u_v = p.dfs; if (dist.get(u) + weight_u_v < dist.get(v)) { // if can relax // (note: Record SP spanning tree here if needed. This is similar) dist.set(v, dist.get(u) + weight_u_v); // relax pq.offer(new IntegerPair(v, dist.get(v))); // (as printpath in BFS) // enqueue this neighbor regardless whether it is already in pq or not } } } for (int i = 0; i < V; i++) // index + 1 for final answer System.out.printf("SSSP(%d, %d) = %d\n", s, i, dist.get(i)); }
private void visit(EdgeWeightedGraph G, int v) { marked[v] = true; for (Edge e : G.adj(v)) { if (!marked[e.other(v)]) pq.offer(e); } }
/** * routing using A* algorithm http://en.wikipedia.org/wiki/A*_search_algorithm * * @param startNode * @param endNode * @param startTime * @param dayIndex * @param pathNodeList return path * @return */ public static double routingAStar( long startNode, long endNode, int startTime, int dayIndex, ArrayList<Long> pathNodeList) { // System.out.println("start finding the path..."); int debug = 0; double totalCost = -1; try { // test store transversal nodes // HashSet<Long> transversalSet = new HashSet<Long>(); if (!OSMData.nodeHashMap.containsKey(startNode) || !OSMData.nodeHashMap.containsKey(endNode)) { System.err.println("cannot find start or end node!"); return -1; } if (startNode == endNode) { System.out.println("start node is the same as end node."); return 0; } HashSet<Long> closedSet = new HashSet<Long>(); HashMap<Long, NodeInfoHelper> nodeHelperCache = new HashMap<Long, NodeInfoHelper>(); PriorityQueue<NodeInfoHelper> openSet = initialStartSet(startNode, endNode, startTime, dayIndex, nodeHelperCache); HashSet<Long> endSet = initialEndSet(endNode); NodeInfoHelper current = null; while (!openSet.isEmpty()) { // remove current from openset current = openSet.poll(); // if(!transversalSet.contains(current.getNodeId())) // transversalSet.add(current.getNodeId()); long nodeId = current.getNodeId(); // add current to closedset closedSet.add(nodeId); if (endSet.contains(nodeId)) { // find the destination current = current.getEndNodeHelper(endNode); totalCost = current.getCost(); break; } // for time dependent routing int timeIndex = startTime + (int) (current.getCost() / OSMParam.SECOND_PER_MINUTE / OSMRouteParam.TIME_INTERVAL); if (timeIndex > OSMRouteParam.TIME_RANGE - 1) // time [6am - 9 pm], we regard times after 9pm as constant edge weights timeIndex = OSMRouteParam.TIME_RANGE - 1; LinkedList<ToNodeInfo> adjNodeList = OSMData.adjListHashMap.get(nodeId); if (adjNodeList == null) continue; // this node cannot go anywhere double arriveTime = current.getCost(); // for each neighbor in neighbor_nodes(current) for (ToNodeInfo toNode : adjNodeList) { debug++; long toNodeId = toNode.getNodeId(); int travelTime; if (toNode.isFix()) // fix time travelTime = toNode.getTravelTime(); else // fetch from time array travelTime = toNode.getSpecificTravelTime(dayIndex, timeIndex); // tentative_g_score := g_score[current] + dist_between(current,neighbor) double costTime = arriveTime + (double) travelTime / OSMParam.MILLI_PER_SECOND; // tentative_f_score := tentative_g_score + heuristic_cost_estimate(neighbor, goal) double heuristicTime = estimateHeuristic(toNodeId, endNode); double totalCostTime = costTime + heuristicTime; // if neighbor in closedset and tentative_f_score >= f_score[neighbor] if (closedSet.contains(toNodeId) && nodeHelperCache.get(toNodeId).getTotalCost() <= totalCostTime) { continue; } NodeInfoHelper node = null; // if neighbor not in openset or tentative_f_score < f_score[neighbor] if (!nodeHelperCache.containsKey(toNodeId)) { // neighbor not in openset node = new NodeInfoHelper(toNodeId); nodeHelperCache.put(node.getNodeId(), node); } else if (nodeHelperCache.get(toNodeId).getTotalCost() > totalCostTime) { // neighbor in openset node = nodeHelperCache.get(toNodeId); if (closedSet.contains(toNodeId)) { // neighbor in closeset closedSet.remove(toNodeId); // remove neighbor form colseset } else { openSet.remove(node); } } // neighbor need update if (node != null) { node.setCost(costTime); node.setHeuristic(heuristicTime); node.setParentId(nodeId); openSet.offer(node); // add neighbor to openset again } } } if (totalCost != -1) { long traceNodeId = current.getNodeId(); pathNodeList.add(traceNodeId); // add end node traceNodeId = current.getParentId(); while (traceNodeId != 0) { pathNodeList.add(traceNodeId); // add node current = nodeHelperCache.get(traceNodeId); traceNodeId = current.getParentId(); } Collections.reverse(pathNodeList); // reverse the path list // System.out.println("find the path successful!"); } else { System.out.println("can not find the path!"); } // OSMOutput.generateTransversalNodeKML(transversalSet, nodeHashMap); } catch (Exception e) { e.printStackTrace(); System.err.println( "tdsp: debug code " + debug + ", start node " + startNode + ", end node " + endNode); } return totalCost; }
@Override public void run() { // TODO Auto-generated method stub PriorityQueue<NodeInfoHelper> openSet = new PriorityQueue<NodeInfoHelper>( 10000, new Comparator<NodeInfoHelper>() { public int compare(NodeInfoHelper n1, NodeInfoHelper n2) { return (int) (n1.getTotalCost() - n2.getTotalCost()); } }); HashSet<Long> closedSet = new HashSet<Long>(); initialEndSet(startNode, endNode, openSet, nodeHelperCache); NodeInfoHelper current = null; // HashSet<Long> transversalSet = new HashSet<Long>(); while (!openSet.isEmpty()) { // remove current from openset current = openSet.poll(); long nodeId = current.getNodeId(); // transversalSet.add(nodeId); // add current to closedset closedSet.add(nodeId); // check if forward searching finish if (sharingData.isSearchingFinish()) break; // add to reverse cover nodes, only add the nodes on the highway if (current.getCurrentLevel() == 1) sharingData.addReverseNode(nodeId); NodeInfo fromNodeInfo = OSMData.nodeHashMap.get(nodeId); LinkedList<ToNodeInfo> adjNodeList = adjListHashMap.get(nodeId); if (adjNodeList == null) continue; // this node cannot go anywhere double arriveTime = current.getCost(); // for each neighbor in neighbor_nodes(current) for (ToNodeInfo toNode : adjNodeList) { long toNodeId = toNode.getNodeId(); NodeInfo toNodeInfo = OSMData.nodeHashMap.get(toNodeId); EdgeInfo edgeInfo = fromNodeInfo.getEdgeFromNodes(toNodeInfo); // check if "highway" not found in param, add it // String highway = edgeInfo.getHighway(); int level = 10; if (OSMData.hierarchyHashMap.containsKey(edgeInfo.getHighway())) level = OSMData.hierarchyHashMap.get(edgeInfo.getHighway()); // 1) always level up, e.g. currently in primary, never go secondary // if(level > current.getCurrentLevel()) { // do not level down // continue; // } // 2) keep on highway if (current.getCurrentLevel() == 1 && level > 1) { continue; } int travelTime = toNode.getMinTravelTime(); // tentative_g_score := g_score[current] + dist_between(current,neighbor) double costTime = arriveTime + (double) travelTime / OSMParam.MILLI_PER_SECOND; // tentative_f_score := tentative_g_score + heuristic_cost_estimate(neighbor, goal) double heuristicTime = OSMRouting.estimateHeuristic(toNodeId, endNode); double totalCostTime = costTime + heuristicTime; // if neighbor in closedset and tentative_f_score >= f_score[neighbor] if (closedSet.contains(toNodeId) && nodeHelperCache.get(toNodeId).getTotalCost() <= totalCostTime) { continue; } NodeInfoHelper node = null; // if neighbor not in openset or tentative_f_score < f_score[neighbor] if (!nodeHelperCache.containsKey(toNodeId)) { // neighbor not in openset node = new NodeInfoHelper(toNodeId); nodeHelperCache.put(node.getNodeId(), node); } else if (nodeHelperCache.get(toNodeId).getTotalCost() > totalCostTime) { // neighbor in openset node = nodeHelperCache.get(toNodeId); if (closedSet.contains(toNodeId)) { // neighbor in closeset closedSet.remove(toNodeId); // remove neighbor form colseset } else { openSet.remove(node); } } // neighbor need update if (node != null) { node.setCost(costTime); node.setHeuristic(heuristicTime); node.setCurrentLevel(level); node.setParentId(nodeId); openSet.offer(node); // add neighbor to openset again } } } // OSMOutput.generateTransversalNodeKML(transversalSet, nodeHashMap, "reverse_transversal"); }
@Override public void run() { HashSet<Long> closedSet = new HashSet<Long>(); PriorityQueue<NodeInfoHelper> openSet = OSMRouting.initialStartSet(startNode, endNode, startTime, dayIndex, nodeHelperCache); NodeInfoHelper current = null; // test // HashSet<Long> transversalSet = new HashSet<Long>(); while (!openSet.isEmpty()) { // remove current from openset current = openSet.poll(); long nodeId = current.getNodeId(); // transversalSet.add(nodeId); // add current to closedset closedSet.add(nodeId); // check reverse searching covering nodes if (sharingData.isNodeInReverseSet(nodeId)) { // we found a path, stop here sharingData.addIntersect(nodeId); if (sharingData.isSearchingFinish()) break; else continue; } NodeInfo fromNodeInfo = OSMData.nodeHashMap.get(nodeId); // for time dependent routing in forwarding search int timeIndex = startTime + (int) (current.getCost() / OSMParam.SECOND_PER_MINUTE / OSMRouteParam.TIME_INTERVAL); if (timeIndex > OSMRouteParam.TIME_RANGE - 1) // time [6am - 9 pm], we regard times after 9pm as constant edge weights timeIndex = OSMRouteParam.TIME_RANGE - 1; LinkedList<ToNodeInfo> adjNodeList = adjListHashMap.get(nodeId); if (adjNodeList == null) continue; // this node cannot go anywhere double arriveTime = current.getCost(); // for each neighbor in neighbor_nodes(current) for (ToNodeInfo toNode : adjNodeList) { long toNodeId = toNode.getNodeId(); NodeInfo toNodeInfo = OSMData.nodeHashMap.get(toNodeId); EdgeInfo edgeInfo = fromNodeInfo.getEdgeFromNodes(toNodeInfo); // check if "highway" not found in param, add it // String highway = edgeInfo.getHighway(); int level = 10; if (OSMData.hierarchyHashMap.containsKey(edgeInfo.getHighway())) level = OSMData.hierarchyHashMap.get(edgeInfo.getHighway()); // 1) always level up, e.g. currently in primary, never go secondary // if(level > current.getCurrentLevel()) { // do not level down // continue; // } // 2) keep on highway if (current.getCurrentLevel() == 1 && level > 1) { continue; } int travelTime; // forward searching is time dependent if (toNode.isFix()) // fix time travelTime = toNode.getTravelTime(); else // fetch from time array travelTime = toNode.getSpecificTravelTime(dayIndex, timeIndex); // tentative_g_score := g_score[current] + dist_between(current,neighbor) double costTime = arriveTime + (double) travelTime / OSMParam.MILLI_PER_SECOND; // tentative_f_score := tentative_g_score + heuristic_cost_estimate(neighbor, goal) double heuristicTime = OSMRouting.estimateHeuristic(toNodeId, endNode); double totalCostTime = costTime + heuristicTime; // if neighbor in closedset and tentative_f_score >= f_score[neighbor] if (closedSet.contains(toNodeId) && nodeHelperCache.get(toNodeId).getTotalCost() <= totalCostTime) { continue; } NodeInfoHelper node = null; // if neighbor not in openset or tentative_f_score < f_score[neighbor] if (!nodeHelperCache.containsKey(toNodeId)) { // neighbor not in openset node = new NodeInfoHelper(toNodeId); nodeHelperCache.put(node.getNodeId(), node); } else if (nodeHelperCache.get(toNodeId).getTotalCost() > totalCostTime) { // neighbor in openset node = nodeHelperCache.get(toNodeId); if (closedSet.contains(toNodeId)) { // neighbor in closeset closedSet.remove(toNodeId); // remove neighbor form colseset } else { openSet.remove(node); } } // neighbor need update if (node != null) { node.setCost(costTime); node.setHeuristic(heuristicTime); node.setCurrentLevel(level); node.setParentId(nodeId); openSet.offer(node); // add neighbor to openset again } } } // test // OSMOutput.generateTransversalNodeKML(transversalSet, "forward_transversal"); }
public ArrayList<ArrayList<Integer>> buildingOutline(int[][] buildings) { // buildings [[1,3,3], [2,4,4], [5,6,1]] => temp [[1,2,3],[2,3,4],[3,4,4],[5,6,1]] => result // [[1,2,3],[2,4,4],[5,6,1]] ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); ArrayList<ArrayList<Integer>> temp = new ArrayList<ArrayList<Integer>>(); if (buildings == null || buildings.length == 0) return result; int n = buildings.length; Point[] points = new Point[2 * n]; for (int i = 0; i < n; i++) { points[2 * i] = new Point(buildings[i][0], true, buildings[i]); points[2 * i + 1] = new Point(buildings[i][1], false, buildings[i]); } Comparator<Point> c1 = new Comparator<Point>() { public int compare(Point p1, Point p2) { return p1.pos - p2.pos; } }; Arrays.sort(points, c1); // sort points in ascending order Comparator<int[]> c2 = new Comparator<int[]>() { public int compare(int[] a, int[] b) { return b[2] - a[2]; } }; PriorityQueue<int[]> pq = new PriorityQueue<int[]>(1, c2); // max heap of buildings int open = 1, pre = points[0].pos, i = 1; pq.offer(points[0].building); while (i < 2 * n) { Point cur = points[i++]; if (open == 0) { pre = cur.pos; } if (pre != cur.pos) { ArrayList<Integer> newB = new ArrayList<Integer>(); newB.add(pre); newB.add(cur.pos); newB.add(pq.peek()[2]); temp.add(newB); pre = cur.pos; } if (cur.isS) { open++; pq.offer(cur.building); } else { open--; pq.remove(cur.building); } } // merge the adjacent outlines if they have the same height if (temp.size() == 0) return result; ArrayList<Integer> preB = temp.get(0); int s = preB.get(0), h = preB.get(2); int m = temp.size(); for (int j = 1; j < m; j++) { if (temp.get(j).get(2) != h) { ArrayList<Integer> path = new ArrayList<Integer>(); path.add(s); // start position path.add(temp.get(j - 1).get(1)); // end position path.add(h); // height result.add(path); s = temp.get(j).get(0); h = temp.get(j).get(2); } } ArrayList<Integer> path = new ArrayList<Integer>(); path.add(s); path.add(temp.get(m - 1).get(1)); path.add(h); result.add(path); return result; }
public static void add(UrlValue url) { if (url != null && !url.url.trim().equals("") && !visitedUrl.contains(url.url)) { url.url = url.url.trim(); pq.offer(url); } }
public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader(new File(args[0]))); BufferedWriter bw = new BufferedWriter(new FileWriter(args[1])); int T = Integer.parseInt(br.readLine()); for (int t = 1; t <= T; t++) { br.readLine(); List<List<Station>> graph = new ArrayList<>(); int N = Integer.parseInt(br.readLine()); for (int i = 0; i < N; i++) { graph.add(new ArrayList<>()); String[] line1 = br.readLine().split(" "); int SN = Integer.parseInt(line1[0]); int W = Integer.parseInt(line1[1]); for (int j = 0; j < SN; j++) { graph.get(i).add(new Station(i, j, W)); } String[] dist = br.readLine().split(" "); for (int j = 0; j < dist.length; j++) { int d = Integer.parseInt(dist[j]); Station s1 = graph.get(i).get(j); Station s2 = graph.get(i).get(j + 1); s1.neighbors.put(s2, d); s2.neighbors.put(s1, d); } } int tunnelNum = Integer.parseInt(br.readLine()); for (int i = 0; i < tunnelNum; i++) { String[] tunnel = br.readLine().split(" "); int l1 = Integer.parseInt(tunnel[0]) - 1; int s1 = Integer.parseInt(tunnel[1]) - 1; int l2 = Integer.parseInt(tunnel[2]) - 1; int s2 = Integer.parseInt(tunnel[3]) - 1; int d = Integer.parseInt(tunnel[4]); Station sta1 = graph.get(l1).get(s1); Station sta2 = graph.get(l2).get(s2); sta1.neighbors.put(sta2, d + sta2.waitTime); // add wait time to distance sta2.neighbors.put(sta1, d + sta1.waitTime); Station sta11 = sta1.cloneForTunnel(); Station sta22 = sta2.cloneForTunnel(); graph.get(sta1.lineNo).add(sta11); graph.get(sta2.lineNo).add(sta22); for (Station st : sta11.neighbors.keySet()) { sta2.neighbors.put( st, d + sta11.neighbors.get( st)); // don't wait, sta11 means go xsfrom sta2 to sta1 than go to other // tunnel } for (Station st : sta22.neighbors.keySet()) { sta1.neighbors.put(st, d + sta22.neighbors.get(st)); } } int queryNum = Integer.parseInt(br.readLine()); bw.write("Case: #" + t + ":"); bw.newLine(); for (int i = 0; i < queryNum; i++) { String[] query = br.readLine().split(" "); int l1 = Integer.parseInt(query[0]) - 1; int s1 = Integer.parseInt(query[1]) - 1; int l2 = Integer.parseInt(query[2]) - 1; int s2 = Integer.parseInt(query[3]) - 1; Station sta1 = graph.get(l1).get(s1); Station sta2 = graph.get(l2).get(s2); PriorityQueue<Station> pq = new PriorityQueue<>(); sta1.dist = sta1.waitTime; for (List<Station> line : graph) { for (Station st : line) { pq.offer(st); } } Set<Station> visited = new HashSet<>(); visited.add(sta1); boolean done = false; while (!done && !pq.isEmpty()) { Station st = pq.poll(); for (Station neb : st.neighbors.keySet()) { if (!visited.contains(neb)) { neb.dist = st.dist + st.neighbors.get(neb); if (neb == sta2) { // reference to same object done = true; break; } visited.add(neb); pq.remove(neb); // because need to let pq update this item's priority level pq.offer(neb); } } } int ret = sta2.dist == Integer.MAX_VALUE ? -1 : sta2.dist; bw.write("" + ret); bw.newLine(); } } bw.close(); br.close(); }
private void addIfNotEmpty(final ComparableIterator iterator) { if (iterator.hasNext()) queue.offer(iterator); else iterator.close(); }