static void test00() { Aron.beg(); PriorityQueue<Interval> queue = new PriorityQueue<Interval>(); Stack<Interval> stack = new Stack<Interval>(); int[] arr1 = {4, 1, 2, 6, 9}; int[] arr2 = {5, 1, 4, 9, 10}; for (int i = 0; i < arr1.length; i++) { queue.add(new Interval(arr1[i], arr2[i])); } if (queue.size() > 0) { stack.push(queue.remove()); } while (!queue.isEmpty()) { Interval top = stack.peek(); Interval inter = queue.remove(); if (top.end < inter.begin) stack.push(inter); else { stack.peek().end = Math.max(stack.peek().end, inter.end); } } while (!stack.empty()) { System.out.println("[" + stack.peek().begin + " " + stack.peek().end + "]"); stack.pop(); } Aron.end(); }
private void removeBuildings( PriorityQueue<Building> endings, PriorityQueue<Integer> heights, List<int[]> result) { final Building rm = endings.poll(); heights.remove(rm.height); while (endings.size() > 0 && endings.peek().to == rm.to) { heights.remove(endings.poll().height); } final int peek = heights.size() > 0 ? heights.peek() : 0; if (peek < rm.height) { result.add(new int[] {rm.to, peek}); } }
// Busqueda usando A* public static int search() { HashSet<State> v = new HashSet<>(); Giros mano = new Giros(); ArrayList<int[][]>aux; finall = inicial.createGoalState(); Q.add(inicial); Node actual; int cont = 0; while ( !(actual = Q.remove()).estado.equals(finall.estado) ) { if(v.contains(actual.estado)) continue; System.out.println(actual.estado+" "+actual.costo_hasta_aqui+" "+actual.costo_total); System.out.println("->\n"+((NodeCubo)actual).getValue() ); v.add(actual.estado); int ca = actual.costo_hasta_aqui + 1; //Realiza Movimientos for( int i=0; i<12; i++ ){ aux = mano.girar( ((Cubo)actual.getValue()).getCubo(), i); Node nuevo = new NodeCubo(ca, ca+Heuristica.h1((Cubo)actual.getValue()), new Cubo( aux, ((Cubo)inicial.getValue()).getColors() ) ); Q.add( (Node)nuevo ); } cont++; } return cont; }
private int getMyTarget(int[] shotAt) { /*PriorityTuple firstTuple=priorityList.remove(); if(shotAt[firstTuple.getPlayerId()]>0) return firstTuple.getPlayerId(); PriorityTuple nextTuple; if(priorityList.size()!=0) nextTuple=priorityList.remove(); while(nextTuple.getPriority()==firstTuple.getPriority()) { if(shotAt[firstTuple.getPlayerId()]<shotAt[nextTuple.getPlayerId()]) return nextTuple.getPlayerId(); if(priorityList.size()!=0) nextTuple=priorityList.remove(); else break; } return firstTuple.getPlayerId();*/ return priorityList.remove().getPlayerId(); }
public int[] maxSlidingWindow(int[] nums, int k) { if (nums == null || nums.length == 0) { return new int[0]; } int len = nums.length; int max = Integer.MIN_VALUE; PriorityQueue<Integer> heap = new PriorityQueue<Integer>(k, new heapComparator()); for (int i = 0; i < Math.min(k, len); i++) { heap.add(nums[i]); } if (k >= len) { int[] edge = new int[1]; edge[0] = heap.peek(); return edge; } int[] res = new int[len - k + 1]; int index = 0; for (int i = k; i < len; i++) { res[index] = heap.peek(); index++; heap.remove(nums[i - k]); heap.add(nums[i]); } res[index] = heap.peek(); return res; }
/** * Removes a single instance of the specified element from this queue, if it is present, whether * or not it has expired. */ public boolean remove(Object o) { final ReentrantLock lock = this.lock; lock.lock(); try { return q.remove(o); } finally { lock.unlock(); } }
public static String next() { if (pq.peek() != null) { System.out.println("queue pop"); String curUrl = pq.remove().url; if (!visitedUrl.contains(curUrl)) { visitedUrl.add(curUrl); return curUrl; } else return null; } else return null; }
public int dijkstra(Vertex s) { int count; Collection<Vertex> vertices_; Comparator<Vertex> comp; PriorityQueue<Vertex> fringe; count = 0; vertices_ = vertices.values(); comp = new Comparator<Vertex>() { public int compare(Vertex i, Vertex j) { return (i.cost - j.cost); } }; fringe = new PriorityQueue<Vertex>(20, comp); for (Vertex v : vertices_) { v.visited = false; v.cost = 999999; } s.cost = 0; s.parent = null; fringe.add(s); while (!fringe.isEmpty()) { Vertex v = fringe.remove(); // lowest-cost count++; // count nodes if (!v.visited) { v.visited = true; for (Edge e : v.edges) { int newcost = v.cost + e.cost; if (newcost < e.target.cost) { if (e.target.cost < 999999) // target on queue already? fringe.remove(e.target); // if yes, remove it. e.target.cost = newcost; e.target.parent = v; fringe.add(e.target); } } } } return count; }
public static void main(String[] args) { PriorityQueue<GregorianCalendar> pq = new PriorityQueue<GregorianCalendar>(); // 优先级队列对GC设置优先级:月->日 pq.add(new GregorianCalendar(1906, Calendar.DECEMBER, 9)); // G. Hopper pq.add(new GregorianCalendar(1815, Calendar.DECEMBER, 10)); // A. Lovelace pq.add(new GregorianCalendar(1923, Calendar.DECEMBER, 3)); // J. von Neumann pq.add(new GregorianCalendar(1910, Calendar.JUNE, 22)); // K. Zuse System.out.println("Iterating over elements..."); for (GregorianCalendar date : pq) System.out.println(date.get(Calendar.YEAR)); System.out.println("Removing elements..."); while (!pq.isEmpty()) System.out.println(pq.remove().get(Calendar.YEAR)); }
// 保存待访问的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(); }
/* * 获取客户极坐标的排序 * * */ public Queue<Client> sortClientsByPolarCoordinate(Client[] clients) { Queue<Client> queue = new LinkedList<Client>(); ClientPolarCoordinateComparator clientPolarCoordinateComparator = new ClientPolarCoordinateComparator(); PriorityQueue<Client> priorityQueue = new PriorityQueue<Client>(clients.length - 1, clientPolarCoordinateComparator); for (int i = 1; i < clients.length; i++) { priorityQueue.add(clients[i]); } while (!priorityQueue.isEmpty()) { queue.add(priorityQueue.remove()); } return queue; }
/** * 执行KNN算法,获取测试元组的类别 * * @param list 训练数据集 * @param test 测试元组 * @param k 设定的K值 * @return 测试元组的类别 */ public String knn(List<List<Double>> list, List<Double> test, int k) { PriorityQueue<KNNNode> pq = new PriorityQueue<KNNNode>(k, comparator); for (int i = 0; i < k; i++) { List<Double> trainTuple = list.get(i); Double c = trainTuple.get(0); KNNNode node = new KNNNode(i, getDistance(test, trainTuple), c); pq.add(node); } for (int i = 0; i < list.size(); i++) { List<Double> t = list.get(i); double distance = getDistance(test, t); KNNNode top = pq.peek(); if (top.getDistance() > distance) { pq.remove(); pq.add(new KNNNode(i, distance, t.get(0))); } } return getMostClass(pq); }
public int[] maxSlidingWindow(int[] nums, int k) { int n = nums.length; if (n == 0) return new int[0]; PriorityQueue<Integer> pq = new PriorityQueue<>(k, Collections.reverseOrder()); Deque<Integer> queue = new ArrayDeque<>(); for (int i = 0; i < k; ++i) { add(pq, queue, nums[i]); } if (n == k) return new int[] {pq.poll().intValue()}; int[] max = new int[n - k + 1]; int idx = 0; for (int i = k; i < n; ++i) { max[idx++] = pq.peek().intValue(); pq.remove(queue.poll()); add(pq, queue, nums[i]); } max[idx] = pq.peek().intValue(); return max; }
public int astar(Vertex start, Vertex goal, Heuristic h) { int count; Collection<Vertex> vertices_; Comparator<Vertex> comp; PriorityQueue<Vertex> fringe; count = 0; vertices_ = vertices.values(); comp = new Comparator<Vertex>() { public int compare(Vertex i, Vertex j) { return (i.cost + i.estimate - j.cost - j.estimate); } }; // use estimates fringe = new PriorityQueue<Vertex>(20, comp); for (Vertex v : vertices_) { v.visited = false; v.cost = 999999; } start.cost = 0; start.parent = null; fringe.add(start); while (!fringe.isEmpty()) { Vertex v = fringe.remove(); // lowest-cost count++; // count nodes if (v.equals(goal)) { // if the goal is found, quit break; } if (!v.visited) { v.visited = true; for (Edge e : v.edges) { int newcost = v.cost + e.cost; if (newcost < e.target.cost) { e.target.cost = newcost; e.target.parent = v; e.target.estimate = h.fn(e.target, goal); // use heuristic fringe.add(e.target); } } } } return count; }
public static void computePaths(City source) { source.minDistance = 0.; PriorityQueue<City> cityQueue = new PriorityQueue<City>(); cityQueue.add(source); while (!cityQueue.isEmpty()) { City u = cityQueue.poll(); // Visit each edge exiting u for (Route e : u.neighbours) { City v = e.target; double weight = e.weight; double distanceThroughU = u.minDistance + weight; if (distanceThroughU < v.minDistance) { cityQueue.remove(v); v.minDistance = distanceThroughU; v.previous = u; cityQueue.add(v); } } } }
/** * 获取所得到的k个最近邻元组的多数类 * * @param pq 存储k个最近近邻元组的优先级队列 * @return 多数类的名称 */ private String getMostClass(PriorityQueue<KNNNode> pq) { Map<Double, Integer> classCount = new HashMap<Double, Integer>(); for (int i = 0; i < pq.size(); i++) { KNNNode node = pq.remove(); double c = node.getC(); if (classCount.containsKey(c)) { classCount.put(c, classCount.get(c) + 1); } else { classCount.put(c, 1); } } int maxIndex = -1; int maxCount = 0; Object[] classes = classCount.keySet().toArray(); for (int i = 0; i < classes.length; i++) { if (classCount.get(classes[i]) > maxCount) { maxIndex = i; maxCount = classCount.get(classes[i]); } } return classes[maxIndex].toString(); }
public int prim(Vertex s) { int cost; Collection<Vertex> vertices_; Comparator<Vertex> comp; PriorityQueue<Vertex> fringe; cost = 0; vertices_ = vertices.values(); comp = new Comparator<Vertex>() { public int compare(Vertex i, Vertex j) { return (i.cost - j.cost); } }; fringe = new PriorityQueue<Vertex>(20, comp); for (Vertex v : vertices_) { v.visited = false; v.parent = null; v.cost = 999999; } s.cost = 0; fringe.add(s); while (!fringe.isEmpty()) { Vertex v = fringe.remove(); // lowest-cost if (!v.visited) { v.visited = true; cost += v.cost(); // calculate cost for (Edge e : v.edges) { if ((!e.target.visited) && (e.cost < e.target.cost)) { e.target.cost = e.cost; e.target.parent = v; fringe.add(e.target); } } } } return cost; }
public static void print() { while (pq.peek() != null) { System.out.println(pq.remove().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(); }
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; }
/** ***************************************************************************** */ void addEntry(String s) { // System.err.println("TRACX: " + s); if (trace_writer != null) trace_writer.println(s); char s0 = s.charAt(0); if (s0 == 'T') { // THREAD if (thread_entries != null) { for (TraceEntry te : thread_entries) pending_entries.add(te); thread_entries = null; } StringTokenizer tok = new StringTokenizer(s); tok.nextToken(); int id = Integer.parseInt(tok.nextToken()); current_thread = thread_map.get(id); if (current_thread == null) { int tid = Integer.parseInt(tok.nextToken()); String tnm = tok.nextToken("\n"); current_thread = new ThreadData(++thread_counter, tid, tnm); thread_map.put(id, current_thread); } thread_entries = new ArrayList<TraceEntry>(); } else if (s0 == 'D') { // DONE if (trace_writer != null) trace_writer.flush(); if (thread_entries != null) { for (TraceEntry te : thread_entries) pending_entries.add(te); thread_entries = null; } StringTokenizer tok = new StringTokenizer(s); tok.nextToken(); long time = Long.parseLong(tok.nextToken()); if (next_time != 0) { int ct = 0; // System.err.println("TRACE: Pending size = " + pending_entries.size()); while (!pending_entries.isEmpty() && pending_entries.peek().getTime() < next_time) { TraceEntry te = pending_entries.remove(); ++ct; outputEntry(te); } if (ct > 0) { for (BdynEventUpdater eu : update_listeners) { eu.eventsAdded(); } } end_time = Math.max(next_time, end_time); } next_time = time; } else if (s0 == 'S') { if (cpu_time == null) { StringTokenizer tok = new StringTokenizer(s); tok.nextToken(); cpu_time = Boolean.parseBoolean(tok.nextToken()); } } else if (cpu_time != null) { TraceEntry te = new TraceEntry(s, current_thread, cpu_time); if (thread_entries == null) pending_entries.add(te); else { thread_entries.add(te); if (te.isExit()) { int sz = thread_entries.size(); int loc = te.getEntryLocation(); if (sz >= 4) { TraceEntry t3 = thread_entries.get(sz - 2); if (!t3.isExit() && t3.getEntryLocation() == loc) { TraceEntry t2 = thread_entries.get(sz - 3); if (t2.isExit() && t2.getEntryLocation() == loc) { TraceEntry t1 = thread_entries.get(sz - 4); if (!t1.isExit() && t1.getEntryLocation() == loc && (te.getTime() - t1.getTime()) < MERGE_TIME) { t1.merge(t2.getTime(), t3.getTime(), te.getTime()); thread_entries.remove(sz - 2); thread_entries.remove(sz - 3); } } } } } } } }
// Pick a target to shoot // Parameters: // prevRound - an array of previous shoots, prevRound[i] is the player that player i shot // -1 if player i did not shoot // alive - an array of player's status, true if the player is still alive in this round // Return: // int - the player id to shoot, return -1 if do not shoot anyone // public int shoot(int[] prevRound, boolean[] alive) { if (prevRound == null) { return -1; // Make love, not war } System.out.println(Arrays.toString(friends)); // Keep track of who got shot, how many times earlier boolean[] shotAt = new boolean[prevRound.length]; int[] shotBy = new int[prevRound.length]; Arrays.fill(shotBy, -1); for (int player = 0; player < prevRound.length; player++) { if (prevRound[player] == -1) continue; shotBy[prevRound[player]] = player; shotAt[prevRound[player]] = true; } // bingyi for (int player = 0; player < prevRound.length; player++) record.get(player).add(prevRound[player]); // yash // call prediction function here predictNextRound(next_round, record, alive); // summing up next_round stats double[] next_round_sum = new double[nplayers]; // add the columns of prediction matrix to get player most likely to be shot at for (int i = 0; i < nplayers; i++) { for (int j = 0; j < nplayers; j++) { next_round_sum[i] += next_round[j][i]; } } // d System.out.println("Typical " + Arrays.toString(next_round_sum)); for (int player = 0; player < prevRound.length; player++) { if (prevRound[player] != -1) whoShotWhomCount[player][prevRound[player]]++; gaugeSeverity(player, prevRound[player], alive, shotAt, shotBy, prevRound, next_round_sum); } // you shoot; he's still alive if (prevRound[this.id] != -1 && alive[prevRound[this.id]]) { priorityList.add(new PriorityTuple(prevRound[this.id], CON)); } // Printing the next_round_sum array returned for (int i = 0; i < next_round.length; i++) { for (int j = 0; j < next_round.length; j++) { System.out.print(next_round[i][j]); } System.out.println(); } /* int popular_target[]=new int[prevRound.length]; int players[]=new int[prevRound.length]; for(int i=0;i<players.length;i++) { players[i]=i; } //sort player and popular_target arrays to get sorted list of targets for(int i=0;i<popular_target.length;i++) { for(int j=0;j<popular_target.length-1;j++) { if(popular_target[j]<popular_target[j+1]) { int temp=popular_target[j]; popular_target[j]=popular_target[j+1]; popular_target[j+1]=temp; temp=players[j]; players[j]=players[j+1]; players[j+1]=temp; } } } //We only need the most likely target, but I'm sorting the list just to get an idea of what our targets are like //printing players and their likeliness to be shot for(int j=0;j<prediction.length;j++) { System.out.print("("+players[j]+","+popular_target[j]+") "); } System.out.println(); */ /* //shoot the most likely player if he is not a friend for(int i=0;i<popular_target.length;i++) { // if((isEnemy(players[i]) || isNeutral(players[i])) && players[i]!=this.id && alive[players[i]]) if((isEnemy(players[i]) || Enemyus(players[i], record) || EnemyourAF(players[i], record, alive))&& players[i]!=this.id && alive[players[i]]) { return players[i]; } } */ // Choose whom to shoot // if no enemies or neutrals are to be shot at if (priorityList.size() == 0) { priorityList.clear(); return -1; } // yash // ArrayList<Integer> targets=new ArrayList<Integer>(); int target; PriorityTuple firstTuple; double maxNextRoundSum; try { do { firstTuple = priorityList.remove(); maxNextRoundSum = next_round_sum[firstTuple.playerId]; target = firstTuple.playerId; // targets.add(firstTuple.playerId); } while (isFriend(target)); } catch (NullPointerException e) { return -1; } while (priorityList.size() != 0 && firstTuple.priority == priorityList.peek().priority) { PriorityTuple anotherTuple = priorityList.remove(); // targets.add(tupleToAdd.playerId); if (next_round_sum[anotherTuple.playerId] > maxNextRoundSum) { maxNextRoundSum = next_round_sum[anotherTuple.playerId]; target = anotherTuple.playerId; } } priorityList.clear(); return target; // System.out.println("this is our hate most list\n"); // printListofArray(hate_most); // if(priorityList.size()==0) // return -1; // // attentionSeekingPrint(priorityList.toString()); // int myTarget=getMyTarget(shotAt); // priorityList.clear(); // //bingyi // printMatrix(record); // //bingyi // return myTarget; }
private List<Haplotype> computeHaplotypes( final ReadBackedPileup pileup, final int contextSize, final int locus, final VariantContext vc) { // Compute all possible haplotypes consistent with current pileup int haplotypesToCompute = vc.getAlternateAlleles().size() + 1; final PriorityQueue<Haplotype> candidateHaplotypeQueue = new PriorityQueue<Haplotype>(100, new HaplotypeComparator()); final PriorityQueue<Haplotype> consensusHaplotypeQueue = new PriorityQueue<Haplotype>( MAX_CONSENSUS_HAPLOTYPES_TO_CONSIDER, new HaplotypeComparator()); for (final PileupElement p : pileup) { final Haplotype haplotypeFromRead = getHaplotypeFromRead(p, contextSize, locus); candidateHaplotypeQueue.add(haplotypeFromRead); } // Now that priority queue has been built with all reads at context, we need to merge and find // possible segregating haplotypes Haplotype elem; while ((elem = candidateHaplotypeQueue.poll()) != null) { boolean foundHaplotypeMatch = false; Haplotype lastCheckedHaplotype = null; for (final Haplotype haplotypeFromList : consensusHaplotypeQueue) { final Haplotype consensusHaplotype = getConsensusHaplotype(elem, haplotypeFromList); if (consensusHaplotype != null) { foundHaplotypeMatch = true; if (consensusHaplotype.getQualitySum() > haplotypeFromList.getQualitySum()) { consensusHaplotypeQueue.remove(haplotypeFromList); consensusHaplotypeQueue.add(consensusHaplotype); } break; } else { lastCheckedHaplotype = haplotypeFromList; } } if (!foundHaplotypeMatch && consensusHaplotypeQueue.size() < MAX_CONSENSUS_HAPLOTYPES_TO_CONSIDER) { consensusHaplotypeQueue.add(elem); } else if (!foundHaplotypeMatch && lastCheckedHaplotype != null && elem.getQualitySum() > lastCheckedHaplotype.getQualitySum()) { consensusHaplotypeQueue.remove(lastCheckedHaplotype); consensusHaplotypeQueue.add(elem); } } // Now retrieve the N most popular haplotypes if (consensusHaplotypeQueue.size() > 0) { // The consensus haplotypes are in a quality-ordered priority queue, so the best haplotypes // are just the ones at the front of the queue final Haplotype haplotype1 = consensusHaplotypeQueue.poll(); List<Haplotype> hlist = new ArrayList<Haplotype>(); hlist.add(new Haplotype(haplotype1.getBases(), 60)); for (int k = 1; k < haplotypesToCompute; k++) { Haplotype haplotype2 = consensusHaplotypeQueue.poll(); if (haplotype2 == null) { haplotype2 = haplotype1; } // Sometimes only the reference haplotype can be found hlist.add(new Haplotype(haplotype2.getBases(), 20)); } return hlist; } else return null; }
/** * Does Dijkstra and returns the a 1d structure that can be treated as 2d * * @param board * @param hero * @return */ private static List<Vertex> doDijkstra(GameState.Board board, GameState.Hero hero) { List<Vertex> vertexes = new LinkedList<Vertex>(); Vertex me = null; // Build the graph sans edges for (int row = 0; row < board.getSize(); row++) { for (int col = 0; col < board.getSize(); col++) { Vertex v = new Vertex(); GameState.Position pos = new GameState.Position(row, col); int tileStart = row * board.getSize() * 2 + (col * 2); v.setTileType(board.getTiles().substring(tileStart, tileStart + 1 + 1)); v.setPosition(pos); vertexes.add(v); } } // Add in the edges for (int i = 0; i < board.getSize() * board.getSize(); i++) { int row = i % (board.getSize()); int col = i / board.getSize(); Vertex v = vertexes.get(i); // Check: Is this us? if (v.getPosition().getX() == hero.getPos().getX() && v.getPosition().getY() == hero.getPos().getY()) me = v; if (v.getTileType().equals("##") || v.getTileType().equals("[]") || v.getTileType().startsWith("$")) // Impassable tiles link to nowhere. continue; // Make sure not to link to impassable blocks that don't have a function // Make sure you don't link impassable blocks to other blocks (you can't go from the pub to // somewhere else) for (int j = col - 1; j <= col + 1; j += 2) { if (j >= 0 && j < board.getSize()) { Vertex adjacentV = vertexes.get(j * board.getSize() + row); v.getAdjacencies().add(adjacentV); } } for (int j = row - 1; j <= row + 1; j += 2) { if (j >= 0 && j < board.getSize()) { Vertex adjacentV = vertexes.get(col * board.getSize() + j); v.getAdjacencies().add(adjacentV); } } } // Zok, we have a graph constructed. Traverse. PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>(); vertexQueue.add(me); me.setMinDistance(0); while (!vertexQueue.isEmpty()) { Vertex v = vertexQueue.poll(); double distance = v.getMinDistance() + 1; for (Vertex neighbor : v.getAdjacencies()) { if (distance < neighbor.getMinDistance()) { neighbor.setMinDistance(distance); neighbor.setPrevious(v); vertexQueue.remove(neighbor); vertexQueue.add(neighbor); } } } return vertexes; }
/** * 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 List<Vehicle> distribute() { List<Vehicle> vehicles = new LinkedList<Vehicle>(); PriorityQueue<Path> ps = getSavedPaths(); List<Path> paths = new LinkedList<Path>(); Path[] tmpPath = new Path[ps.size()]; for (int j = 0; j < tmpPath.length; j++) { tmpPath[j] = ps.remove(); } for (int j = tmpPath.length - 1; j >= 0; j--) { System.out.println(tmpPath[j]); paths.add(tmpPath[j]); } while (!isDone(vehicles)) { List<Path> p = new LinkedList<Path>(); Vehicle vehicle = new Vehicle(); if (getRemainingRequireMents(vehicles) > Vehicle.getMaxMaxLoad()) { vehicle.setLoad(Vehicle.getMaxMaxLoad()); } else { vehicle.setLoad(getRemainingRequireMents(vehicles)); } Client[] c = new Client[1]; c[0] = clients[0]; vehicle.setClients(c); boolean pathAdded = false; for (int i = 0; i < paths.size(); i++) { Path path = paths.get(i); if (validate(vehicle, p, path)) { p.add(path); // System.out.println("add path " + path); vehicle.setClients(getPath(p)); paths.remove(i); // System.out.println("remove " + path); pathAdded = true; } } if (pathAdded) { vehicles.add(vehicle); } /*将已经配送过的点的边,去掉*/ for (Vehicle v1 : vehicles) { for (Client client : v1.getClients()) { // System.out.println("Client:"+client); Object[] pathsArray = paths.toArray(); for (int i = 0; i < pathsArray.length; i++) { Path path = (Path) pathsArray[i]; // System.out.println("Path to validate "+ path); if ((path.getEnd() == client)) { // System.out.println("end remove " + path); paths.remove(path); } if (path.getStart() == client) { // System.out.println("start remove " + path); paths.remove(path); } } } } /*如果一条边上的点requirement 之和大于vehicle的载重,去掉。*/ Object[] pathArray = paths.toArray(); for (int i = 0; i < pathArray.length; i++) { Path path = (Path) pathArray[i]; if (path.getEnd().getRequirement() + path.getStart().getRequirement() > vehicle.getMaxLoad()) { paths.remove(path); } } // 最后还有一些孤立的配送点需要配送 if (paths.size() == 0) { List<Client> remainingClients = getRemainingClient(vehicles); for (Client client : remainingClients) { Client[] c0 = new Client[3]; c0[0] = clients[0]; c0[1] = client; c0[2] = clients[0]; Vehicle vehicle1 = new Vehicle(); if (getRemainingRequireMents(vehicles) > Vehicle.getMaxMaxLoad()) { vehicle1.setLoad(Vehicle.getMaxMaxLoad()); } else { vehicle1.setLoad(getRemainingRequireMents(vehicles)); } vehicle1.setClients(c0); vehicles.add(vehicle1); } return vehicles; } } return vehicles; }