public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); StringTokenizer st; t = Integer.parseInt(br.readLine()); while (t-- > 0) { st = new StringTokenizer(br.readLine()); n = Integer.parseInt(st.nextToken()); m = Integer.parseInt(st.nextToken()); S = Integer.parseInt(st.nextToken()); T = Integer.parseInt(st.nextToken()); // build graph AdjList = new Vector<Vector<IntegerPair>>(); for (i = 0; i < n; i++) AdjList.add(new Vector<IntegerPair>()); while (m-- > 0) { st = new StringTokenizer(br.readLine()); a = Integer.parseInt(st.nextToken()); b = Integer.parseInt(st.nextToken()); w = Integer.parseInt(st.nextToken()); AdjList.get(a).add(new IntegerPair(b, w)); // bidirectional AdjList.get(b).add(new IntegerPair(a, w)); } // SPFA from source S // initially, only S has dist = 0 and in the queue Vector<Integer> dist = new Vector<Integer>(); for (i = 0; i < n; i++) dist.add(INF); dist.set(S, 0); Queue<Integer> q = new LinkedList<Integer>(); q.offer(S); Vector<Boolean> in_queue = new Vector<Boolean>(); for (i = 0; i < n; i++) in_queue.add(false); in_queue.set(S, true); while (!q.isEmpty()) { int u = q.peek(); q.poll(); in_queue.set(u, false); for (j = 0; j < AdjList.get(u).size(); j++) { // all outgoing edges from u int v = AdjList.get(u).get(j).first(), weight_u_v = AdjList.get(u).get(j).second(); if (dist.get(u) + weight_u_v < dist.get(v)) { // if can relax dist.set(v, dist.get(u) + weight_u_v); // relax if (!in_queue.get(v)) { // add to the queue only if it's not in the queue q.offer(v); in_queue.set(v, true); } } } } pr.printf("Case #%d: ", caseNo++); if (dist.get(T) != INF) pr.printf("%d\n", dist.get(T)); else pr.printf("unreachable\n"); } pr.close(); }
/** * Method description * * @param connectionId * @param packet * @param session * @param repo * @param results * @param settings * @throws PacketErrorTypeException */ @Override public void processFromUserOutPacket( JID connectionId, Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings) throws PacketErrorTypeException { if (session.isLocalDomain(packet.getStanzaTo().getDomain(), false)) { // This is a local user so we can quickly get his vCard from the database try { String strvCard = repo.getPublicData(packet.getStanzaTo().getBareJID(), ID, VCARD_KEY, null); Packet result = null; if (strvCard != null) { result = parseXMLData(strvCard, packet); } else { result = packet.okResult((String) null, 1); } // end of if (vcard != null) result.setPacketTo(connectionId); results.offer(result); } catch (UserNotFoundException e) { results.offer( Authorization.ITEM_NOT_FOUND.getResponseMessage(packet, "User not found", true)); } // end of try-catch } else { // Else forward the packet to a remote server results.offer(packet.copyElementOnly()); } }
public void remove(MUFModule module) { if (playing) { delayRemove.offer(module); return; } // set to true playing = true; adding = false; moduleToBeRemoved = module; // exclude from layout modules.remove(module.getId()); GridData data = (GridData) module.self.getLayoutData(); data.exclude = true; module.self.setLayoutData(data); module.self.setVisible(false); if (content.isVisible()) { // get destination size frame = 1; Point newSize = content.computeSize(SWT.DEFAULT, SWT.DEFAULT); dx = Math.min(0, (newSize.x - oldSize.x) / FRAMES); dy = Math.min(0, (newSize.y - oldSize.y) / FRAMES); Display.getCurrent().timerExec(0, runnable); } else { oldSize = content.computeSize(SWT.DEFAULT, SWT.DEFAULT); playing = false; delayDispose.offer(module.self); } module.dispose(); }
public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> ans = new ArrayList<List<Integer>>(); if (root == null) return ans; Queue<TreeNodeWithLevel> queue = new LinkedList<TreeNodeWithLevel>(); queue.offer(new TreeNodeWithLevel(root, 0)); int preLevel = -1; while (!queue.isEmpty()) { TreeNodeWithLevel head = queue.poll(); TreeNode node = head.node; int level = head.level; if (level == preLevel) { ans.get(preLevel).add(node.val); } else { List<Integer> levelList = new ArrayList<Integer>(); ans.add(levelList); levelList.add(node.val); preLevel = level; } if (node.left != null) { queue.offer(new TreeNodeWithLevel(node.left, level + 1)); } if (node.right != null) { queue.offer(new TreeNodeWithLevel(node.right, level + 1)); } } return ans; }
/** * Search specific element by key and tagName. * * @param root root element * @param key search keyword * @param tagName search tag name * @return search result, null of either input is invalid or the looking result is not found. */ private Element searchForKey(final Element root, final String key, final String tagName) { if (root == null || StringUtils.isEmptyString(key)) { return null; } final Queue<Element> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { final Element pe = queue.poll(); final NodeList pchildrenList = pe.getChildNodes(); for (int i = 0; i < pchildrenList.getLength(); i++) { final Node node = pchildrenList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { queue.offer((Element) node); } } String value = pe.getNodeName(); if (StringUtils.isEmptyString(value) || !value.equals(tagName)) { continue; } value = pe.getAttribute(ATTRIBUTE_NAME_NAME); if (StringUtils.isEmptyString(value)) { continue; } if (value.equals(key)) { return pe; } } return null; }
public static BTNode Insert(BTNode root, int value) { BTNode NewNode = new BTNode(value); // System.out.print(value); if (root == null) { root = NewNode; return root; } Queue<BTNode> q = new LinkedList<BTNode>(); q.offer(root); BTNode current = null; System.out.println("root: " + root.getData() + " "); while (!q.isEmpty()) { current = q.poll(); System.out.print(current.getData() + " "); if (current.getLeft() == null) { current.setLeft(NewNode); return root; } else { q.offer(current.getLeft()); } if (current.getRight() == null) { current.setRight(NewNode); return root; } else { q.offer(current.getRight()); } } return root; }
/* * Serialize uses queue implementation * Time complexity: O(h*2^(h-1)), h is height of binary tree * Extra space: O(2^(h-1)) * * @see SerializeDeserialize#serialize(TreeNode) */ public String serialize(TreeNode root) { // TODO Auto-generated method stub if (root == null) return ""; StringBuilder result = new StringBuilder("["); Queue<TreeNode> curr_lv = new LinkedList<>(); boolean finished = false; curr_lv.offer(root); while (!finished && !curr_lv.isEmpty()) { int size = curr_lv.size(); Queue<TreeNode> next_lv = new LinkedList<>(); finished = true; // System.out.println(Arrays.asList(curr_lv)); while (!curr_lv.isEmpty()) { TreeNode node = curr_lv.poll(); if (node == null) { result.append("null").append(','); continue; } result.append(String.valueOf(node.val)).append(','); if (node.left != null || node.right != null) finished = false; next_lv.offer(node.left); next_lv.offer(node.right); } // System.out.println(result+","+finished); curr_lv = next_lv; } return result.deleteCharAt(result.length() - 1).append(']').toString(); }
// Decodes your encoded data to tree. public TreeNode deserialize(String data) { if (data.equals("#")) return null; String[] num = data.split(","); int count = 0; Queue<TreeNode> q = new LinkedList<>(); TreeNode root = new TreeNode(Integer.parseInt(num[count++])); q.offer(root); while (!q.isEmpty()) { TreeNode cur = q.poll(); if (num[count].equals("#")) { cur.left = null; } else { cur.left = new TreeNode(Integer.parseInt(num[count])); q.offer(cur.left); } count++; if (num[count].equals("#")) { cur.right = null; } else { cur.right = new TreeNode(Integer.parseInt(num[count])); q.offer(cur.right); } count++; } return root; }
// ------------------- Solution 2 -------------------// // BFS: size + queue (ok for most time) public List<List<Integer>> levelOrder2(TreeNode root) { // input validation List<List<Integer>> res = new ArrayList<List<Integer>>(); if (root == null) { return res; } // traverse level by level Queue<TreeNode> q = new LinkedList<TreeNode>(); q.add(root); while (!q.isEmpty()) { List<Integer> item = new ArrayList<Integer>(); int size = q.size(); for (int i = 0; i < size; i++) { TreeNode cur = q.poll(); item.add(cur.val); if (cur.left != null) { q.offer(cur.left); } if (cur.right != null) { q.offer(cur.right); } } res.add(item); } return res; }
public int randomlyGet() { Queue<Node> q = new LinkedList<>(); q.offer(root); int seen = 0; int rValue = root.value; while (!q.isEmpty()) { Node n = q.poll(); if (n != null) { seen += 1; if (rnd.nextInt(seen) == 0) { rValue = n.value; } q.offer(n.left); q.offer(n.right); } } return rValue; }
public void printSliceBySlice() { Queue<Node> q = new LinkedList<>(); q.offer(root); int leftover = 1, next = 0; while (!q.isEmpty()) { Node n = q.poll(); if (n.left != null) { q.offer(n.left); next++; } if (n.right != null) { q.offer(n.right); next++; } System.out.print(n); System.out.print(" "); if (--leftover == 0) { System.out.println(); leftover = next; next = 0; } } }
public void connect(TreeLinkNode root) { if (root == null) { return; } Queue<TreeLinkNode> queue = new LinkedList<TreeLinkNode>(); queue.offer(root); while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { root = queue.poll(); if (i == size - 1) { root.next = null; } else { root.next = queue.peek(); } if (root.left != null) { queue.offer(root.left); } if (root.right != null) { queue.offer(root.right); } } } }
public static void deleteSubTree3(Node[] tree, int index) { Map<Integer, ArrayList<Integer>> pmap = new HashMap<>(); for (int j = 0; j < tree.length; j++) { int p = tree[j].getParent(); if (pmap.containsKey(p)) { pmap.get(p).add(j); } else { ArrayList<Integer> children = new ArrayList<Integer>(); children.add(j); pmap.put(p, children); } } int del_node = index; Queue<Integer> q = new LinkedList<Integer>(); q.offer(del_node); while (!q.isEmpty()) { Integer n = q.poll(); for (int k = 0; k < tree.length; k++) { if (tree[k].getParent() == n.intValue()) { q.offer(k); } } tree[n.intValue()].setValid(false); } }
S bfs() { Set<String> s = new TreeSet<String>(); Queue<S> q = new LinkedList<S>(); q.offer(new S(first, 0, null)); while (!q.isEmpty()) { S k = q.poll(); if (k.str.equals(last)) { if (k.d == 0) { k = new S(last, 1, k); } return k; } char ch[] = k.str.toCharArray(); for (int i = 0; i < ch.length; i++) { ch = k.str.toCharArray(); for (int j = 0; j < 26; j++) { ch[i] = (char) ('a' + j); if (check(String.valueOf(ch), k.str) && (!(s.contains(String.valueOf(ch))))) { s.add(k.str); q.offer(new S(String.valueOf(ch), k.d + 1, k)); } } } } return new S("", 0, null); }
/** * Method description * * @param packet * @param repo * @param results * @param settings * @throws PacketErrorTypeException */ @Override public void processNullSessionPacket( Packet packet, NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings) throws PacketErrorTypeException { if (packet.getType() == StanzaType.get) { try { String strvCard = repo.getPublicData(packet.getStanzaTo().getBareJID(), ID, VCARD_KEY, null); if (strvCard != null) { results.offer(parseXMLData(strvCard, packet)); } else { results.offer(packet.okResult((String) null, 1)); } // end of if (vcard != null) } catch (UserNotFoundException e) { results.offer( Authorization.ITEM_NOT_FOUND.getResponseMessage(packet, "User not found", true)); } // end of try-catch } else { // This is most likely a response to the user from the remote // entity with vCard request results. // Processed in processToUserPacket() method. } }
public boolean LoopIsExist(int start, int end) { if (start == end) return true; Queue<Integer> nodes = new LinkedList<Integer>(); nodes.offer(end); ArrayList<Edge> tmp = new ArrayList<Edge>(); for (int i = 0; i < this.edges.size(); i++) { Edge ee = new Edge(this.edges.get(i).startNode, this.edges.get(i).endNode); tmp.add(ee); } while (nodes.isEmpty() == false) { Integer curNode = nodes.poll(); for (int kkk = 0; kkk < tmp.size(); ) { if (tmp.get(kkk).startNode == curNode) { if (tmp.get(kkk).endNode == start) return true; else { nodes.offer(tmp.get(kkk).endNode); tmp.remove(kkk); } } else { kkk++; } } } return false; }
// Encodes a tree to a single string. public String serialize(TreeNode root) { if (root == null) return "#"; StringBuilder s = new StringBuilder(); Queue<TreeNode> q = new LinkedList<>(); q.add(root); s.append(root.val); while (!q.isEmpty()) { TreeNode curNode = q.poll(); if (curNode.left != null) { s.append("," + curNode.left.val); q.offer(curNode.left); } else { s.append(",#"); } if (curNode.right != null) { s.append("," + curNode.right.val); q.offer(curNode.right); } else { s.append(",#"); } } return s.toString(); }
// ------------------- Solution 2 -------------------// // sentinel -> null (practice your coding capability) public List<List<Integer>> levelOrder3(TreeNode root) { // input validation List<List<Integer>> res = new ArrayList<List<Integer>>(); if (root == null) { return res; } // traverse level by level Queue<TreeNode> q = new LinkedList<TreeNode>(); q.add(root); q.add(null); List<Integer> item = new ArrayList<Integer>(); while (!q.isEmpty()) { // case 1: end of level reached TreeNode cur = q.poll(); if (cur == null) { res.add(new ArrayList<Integer>(item)); // attention, need to new a List item.clear(); if (!q.isEmpty()) { // add sentinel for next level: only when q is not empty!!! q.offer(null); } // case 2: in current level } else { item.add(cur.val); if (cur.left != null) { q.offer(cur.left); } if (cur.right != null) { q.offer(cur.right); } } } return res; }
/** * "Push" new content to consumers: publish to this input stream readers new content to be read * from <code>inputStream</code> parameter. This * * @param inputStream New content for producers * @throws IOException If this input stream was closed. * @throws IllegalArgumentException If <code>inputStream</code> is <code>null</code>. * @see #close() */ public void push(InputStream inputStream) throws IOException { if (inputStream == null) { throw new IllegalArgumentException("Input stream can not be null."); } if (isClosed) { throw new IOException("Stream is closed"); } while (!inputStreamBuffer.offer(inputStream)) { debug("[P] Waiting for a read to complete (" + inputStreamBuffer.size() + ")"); synchronized (consumerMonitor) { consumerMonitor.notifyAll(); } if (!inputStreamBuffer.offer(inputStream)) { synchronized (producerMonitor) { try { producerMonitor.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } } } debug("[P] End of wait"); } debug("[P] Added a new input stream (buffer now has " + inputStreamBuffer.size() + " streams)"); }
/** * @param start, a string * @param end, a string * @param dict, a set of string * @return an integer */ public int ladderLength(String start, String end, Set<String> dict) { Queue<String> queue = new LinkedList<String>(); dict.remove(start); queue.offer(start); int length = 1; while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { String word = queue.poll(); for (int j = 0; j < word.length(); j++) { char[] wordArray = word.toCharArray(); char charAtJ = wordArray[j]; for (char chr = 'a'; chr <= 'z'; chr++) { if (chr == charAtJ) { continue; } wordArray[j] = chr; String temp = String.valueOf(wordArray); if (temp.equals(end)) { return length + 1; } if (dict.contains(temp)) { queue.offer(temp); dict.remove(temp); } } } } length++; } return 0; }
/* * Deserialize using queue * Time complexity : O(n), n is length of data Extra * space: O(n) * * @see SerializeDeserialize#deserialize(java.lang.String) */ public TreeNode deserialize(String data) { // TODO Auto-generated method stub if (data == null || data.length() == 0) return null; String[] node_val = data.substring(1, data.length() - 1).split(","); TreeNode root = new TreeNode(Integer.valueOf(node_val[0])); boolean is_left_child = true; TreeNode parent = null; Queue<TreeNode> q = new LinkedList<>(); q.offer(root); for (int i = 1; i < node_val.length; i++) { TreeNode child = null; if (!node_val[i].equals("null")) { child = new TreeNode(Integer.valueOf(node_val[i])); q.offer(child); } if (is_left_child) { parent = q.poll(); parent.left = child; is_left_child = false; } else { parent.right = child; is_left_child = true; } } return root; }
public int numSquares(int n) { if (n == 0) return 0; Queue<Integer> que = new LinkedList<Integer>(); que.offer(0); boolean visited[] = new boolean[n]; int level = 0; while (!que.isEmpty()) { int size = que.size(); level++; for (int i = 0; i < size; i++) { int curr = que.poll(); for (int j = 1; curr + j * j <= n; j++) { if (curr + j * j == n) return level; if (!visited[curr + j * j]) { que.offer(curr + j * j); visited[curr + j * j] = true; } } } } return -1; }
private static int shortestPath(Node n1, Node n2, Graph g) { Queue<Node> Q = new ArrayDeque<Node>(); Map<Node, Node> V = new HashMap<Node, Node>(); Q.offer(n1); V.put(n1, null); while (!Q.isEmpty()) { Node m = Q.poll(); if (V.containsKey(n2)) break; for (Node p : g.getAdjacentNodes(m)) { if (V.containsKey(p)) continue; Q.offer(p); V.put(p, m); } } int s = 0; do { s++; n2 = V.get(n2); } while (n2 != null); return s; }
/** * Method description * * @param p * @param serv * @param handler * @param results * @return */ @Override public boolean process( Packet p, ComponentIOService serv, ComponentProtocolHandler handler, Queue<Packet> results) { if (p.isXMLNSStaticStr(Iq.IQ_BIND_PATH, XMLNS)) { if ((p.getType() == StanzaType.set) && serv.isAuthenticated()) { String hostname = p.getElemCDataStaticStr(IQ_BIND_HOSTNAME_PATH); handler.bindHostname(hostname, serv); results.offer(Packet.packetInstance(okResult(p.getElement()), null, null)); } else { log.fine("Ok result received: " + p.toString()); } return true; } if (p.isXMLNSStaticStr(IQ_UNBIND_PATH, XMLNS)) { if ((p.getType() == StanzaType.set) && serv.isAuthenticated()) { String hostname = p.getElemCDataStaticStr(IQ_BIND_HOSTNAME_PATH); handler.unbindHostname(hostname, serv); results.offer(Packet.packetInstance(okResult(p.getElement()), null, null)); } else { log.fine("Ok result received: " + p.toString()); } return true; } return false; }
private boolean existsUnblockedSemiDirectedPath(Node from, Node to, List<Node> cond, Graph G) { Queue<Node> Q = new LinkedList<Node>(); Set<Node> V = new HashSet<Node>(); Q.offer(from); V.add(from); while (!Q.isEmpty()) { Node t = Q.remove(); if (t == to) return true; for (Node u : G.getAdjacentNodes(t)) { Edge edge = G.getEdge(t, u); Node c = Edges.traverseSemiDirected(t, edge); if (c == null) continue; if (cond.contains(c)) continue; if (c == to) return true; if (!V.contains(c)) { V.add(c); Q.offer(c); } } } return false; }
public int ladderLength(String start, String end, Set<String> dict) { Queue<String> queue = new LinkedList<String>(); Set<String> searched = new HashSet<String>(); queue.offer(start); searched.add(start); int length = 1; while (!queue.isEmpty()) { int count = queue.size(); while (count > 0) { char[] w = queue.poll().toCharArray(); for (int i = 0; i < w.length; i++) { char tmp = w[i]; for (char c = 'a'; c <= 'z'; c++) { if (tmp == c) continue; w[i] = c; String s = new String(w); if (s.equals(end)) return length + 1; if (dict.contains(s) && !searched.contains(s)) { queue.offer(s); searched.add(s); } } w[i] = tmp; } count--; } length++; } return 0; }
public static void main(String[] args) throws IOException { int n = readInt(); int m = readInt(); ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>(); for (int x = 0; x < n; x++) adj.add(new ArrayList<Integer>()); for (int x = 0; x < m; x++) { int a = readInt() - 1; int b = readInt() - 1; adj.get(a).add(b); adj.get(b).add(a); } int k = readInt(); Queue<State> q = new LinkedList<State>(); boolean[] v = new boolean[n]; for (int x = 0; x < k; x++) { int a = readInt() - 1; v[a] = true; q.offer(new State(a, 0)); } int max = 0; while (!q.isEmpty()) { State curr = q.poll(); max = Math.max(max, curr.moves); for (Integer next : adj.get(curr.index)) { if (v[next]) continue; v[next] = true; q.offer(new State(next, curr.moves + 1)); } } System.out.println(max); }
private void deliverMsg( Queue<GroupStampedMessage> rcvQueue, Queue<GroupStampedMessage> delayQueue, TimeStampedMessage message, Hashtable<String, String> recRuleTable) { synchronized (rcvQueue) { synchronized (delayQueue) { String key = message.getSource() + message.getDest() + message.getKind() + Integer.toString(message.getNum()); // System.out.println(key); String flag = this.checkReceiveRules(recRuleTable, message, key); if (flag.equals("drop")) return; else if (flag.equals("dupe")) { rcvQueue.offer((GroupStampedMessage) message); TimeStampedMessage newMes = new MessagePasser().clone(message); rcvQueue.offer((GroupStampedMessage) newMes); } else if (flag.equals("delay")) { recdelay.offer(message); return; } else { rcvQueue.offer((GroupStampedMessage) message); } while (!recdelay.isEmpty()) { GroupStampedMessage delayMes = groupdelay.poll(); rcvQueue.offer(delayMes); } return; } } }
/** * Breadth first traversal of the topology DAG * * @param topologies * @param td * @param spouts * @return A partial ordering of components */ private Queue<Component> bfs(Topologies topologies, TopologyDetails td, List<Component> spouts) { // Since queue is a interface Queue<Component> ordered__Component_list = new LinkedList<Component>(); HashMap<String, Component> visited = new HashMap<String, Component>(); /* start from each spout that is not visited, each does a breadth-first traverse */ for (Component spout : spouts) { if (!visited.containsKey(spout.id)) { Queue<Component> queue = new LinkedList<Component>(); queue.offer(spout); while (!queue.isEmpty()) { Component comp = queue.poll(); visited.put(comp.id, comp); ordered__Component_list.add(comp); List<String> neighbors = new ArrayList<String>(); neighbors.addAll(comp.children); neighbors.addAll(comp.parents); for (String nbID : neighbors) { if (!visited.containsKey(nbID)) { Component child = topologies.getAllComponents().get(td.getId()).get(nbID); queue.offer(child); } } } } } return ordered__Component_list; }
@Override protected void encode(ChannelHandlerContext ctx, REQUEST msg, List<Object> out) throws Exception { ENCODED request = encodeRequest(ctx, msg); sentRequestQueue.offer(msg); out.add(request); sentRequestTimings.offer(System.nanoTime()); }