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 expect(Class<?> c) { if (!c.isInstance(stack.peek())) { throw new IllegalStateException( "Internal stack error: " + "Expected '" + c.getName() + "' found '" + stack.peek().getClass().getName() + "'"); } }
public static boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') stack.push(s.charAt(i)); else if (s.charAt(i) == ')' && !stack.empty() && stack.peek() == '(') stack.pop(); else if (s.charAt(i) == ']' && !stack.empty() && stack.peek() == '[') stack.pop(); else if (s.charAt(i) == '}' && !stack.empty() && stack.peek() == '{') stack.pop(); else return false; } return stack.empty(); }
public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); // br = new BufferedReader(new FileReader("in.txt")); // out = new PrintWriter(new FileWriter("out.txt")); N = readInt(); val = new int[N]; hi = new int[N]; lo = new int[N]; poss = new ArrayList<ArrayList<Integer>>(); intervals = new TreeSet<Interval>(); for (int i = 0; i < N; i++) val[i] = readInt(); for (int i = 0; i < 2 * N; i++) poss.add(new ArrayList<Integer>()); Stack<State> s = new Stack<State>(); // processing upper bound (first number less than the current number) for (int i = N - 1; i >= 0; i--) { while (!s.isEmpty() && val[i] < s.peek().val) s.pop(); if (s.isEmpty()) hi[val[i]] = N; else hi[val[i]] = s.peek().index; s.push(new State(val[i], i)); } s.clear(); // processing lower bound (last number greater than the current number) for (int i = 0; i < N; i++) { while (!s.isEmpty() && val[i] > s.peek().val) s.pop(); if (s.empty()) lo[val[i]] = -1; else lo[val[i]] = s.peek().index; s.push(new State(val[i], i)); } for (int i = 0; i < N; i++) { int diff = val[i] - i + N - 1; poss.get(diff).add(i); } for (int i = 0; i < 2 * N; i++) { sweep(poss.get(i)); } out.println(intervals.size()); for (Interval i : intervals) out.printf("%d %d\n", i.l + 1, i.r + 1); out.close(); }
public static void main(String[] args) throws StackEmptyException { Stack<Integer> l = new LLStack<Integer>(); // store from back for (int i = args.length - 1; i >= 0; i--) { if (args[i].equals("+")) { add(l); } else if (args[i].equals("-")) { subtract(l); } else if (args[i].equals("x")) { multiply(l); } else if (args[i].equals("/")) { divide(l); } else { try { l.push(Integer.parseInt(args[i])); } catch (NumberFormatException e) { error(); } } } if (l.size() != 1) { error(); } else { System.out.println(l.peek()); } }
private static long evaluateExpression(String expr) { Stack<Long> oper = new Stack<Long>(); Stack<String> op = new Stack<String>(); int i = 0; while (i < expr.length()) { char ch = expr.charAt(i); if (ch >= '0' && ch <= '9') { StringBuffer sb = new StringBuffer(); sb.append(ch); while (++i < expr.length()) { ch = expr.charAt(i); if (ch >= '0' && ch <= '9') { sb.append(ch); } else { break; } } oper.push(Long.parseLong(sb.toString())); if (!op.empty() && ("**".equals(op.peek()))) { oper.push(computeExpression(oper, op.pop())); } if (i == expr.length()) { while (!op.empty() && "*".equals(op.peek())) { oper.push(computeExpression(oper, op.pop())); } } } else if (ch == '*') { StringBuffer sb = new StringBuffer(); sb.append(ch); while (++i < expr.length()) { ch = expr.charAt(i); if (ch == '*') { sb.append(ch); } else { break; } } if (sb.length() > 2) { return -1; } op.push(sb.toString()); } } if (!op.empty() || oper.empty()) return -1; return oper.pop(); }
public void body(BodyDescriptor bd, InputStream in) throws IOException { expect(Part.class); Body body = MimeUtility.decodeBody(in, bd.getTransferEncoding()); try { ((Part) stack.peek()).setBody(body); } catch (MessagingException me) { throw new Error(me); } }
public void preamble(InputStream is) throws IOException { expect(MimeMultipart.class); StringBuffer sb = new StringBuffer(); int b; while ((b = is.read()) != -1) { sb.append((char) b); } ((MimeMultipart) stack.peek()).setPreamble(sb.toString()); }
public void field(String fieldData) { expect(Part.class); try { String[] tokens = fieldData.split(":", 2); ((Part) stack.peek()).addHeader(tokens[0], tokens[1].trim()); } catch (MessagingException me) { throw new Error(me); } }
public void ignorableAtRule(String atRule) throws CSSException { // Create the unknown rule and add it to the rule list CSSUnknownRuleImpl ir = new CSSUnknownRuleImpl(_parentStyleSheet, null, atRule); if (!_nodeStack.empty()) { ((CSSRuleListImpl) _nodeStack.peek()).add(ir); } else { // _nodeStack.push(ir); _root = ir; } }
public void field(RawField field) { expect(Part.class); try { Field parsedField = DefaultFieldParser.parse(field.getRaw(), null); ((Part) stack.peek()).addHeader(parsedField.getName(), parsedField.getBody().trim()); } catch (MessagingException me) { throw new Error(me); } catch (MimeException me) { throw new Error(me); } }
public void startBodyPart() { expect(MimeMultipart.class); try { MimeBodyPart bodyPart = new MimeBodyPart(); ((MimeMultipart) stack.peek()).addBodyPart(bodyPart); stack.push(bodyPart); } catch (MessagingException me) { throw new Error(me); } }
public void flushTagBuffering() { if (!tagMetaStack.isEmpty()) { TagMeta tm = tagMetaStack.peek(); if (tm.bufferMode) { writeTagBodyStart(tm); if (tm.bufferPartNumber != -1) { htmlPartPrintlnRaw(tm.bufferPartNumber); } tm.bufferMode = false; } } }
public void startMultipart(BodyDescriptor bd) { expect(Part.class); Part e = (Part) stack.peek(); try { MimeMultipart multiPart = new MimeMultipart(e.getContentType()); e.setBody(multiPart); stack.push(multiPart); } catch (MessagingException me) { throw new Error(me); } }
private void htmlPartPrintlnToResponse(int partNumber) { if (!tagMetaStack.isEmpty()) { TagMeta tm = tagMetaStack.peek(); if (tm.bufferMode && tm.bufferPartNumber == -1) { tm.bufferPartNumber = partNumber; return; } } flushTagBuffering(); htmlPartPrintlnRaw(partNumber); }
public void importStyle(String uri, SACMediaList media, String defaultNamespaceURI) throws CSSException { // Create the import rule and add it to the rule list CSSImportRuleImpl ir = new CSSImportRuleImpl(_parentStyleSheet, null, uri, new MediaListImpl(media)); if (!_nodeStack.empty()) { ((CSSRuleListImpl) _nodeStack.peek()).add(ir); } else { // _nodeStack.push(ir); _root = ir; } }
public void startPage(String name, String pseudo_page) throws CSSException { // Create the page rule and add it to the rule list CSSPageRuleImpl pr = new CSSPageRuleImpl(_parentStyleSheet, null, name, pseudo_page); if (!_nodeStack.empty()) { ((CSSRuleListImpl) _nodeStack.peek()).add(pr); } // Create the style declaration CSSStyleDeclarationImpl decl = new CSSStyleDeclarationImpl(pr); pr.setStyle(decl); _nodeStack.push(pr); _nodeStack.push(decl); }
void topologicalSort() { Stack s = new Stack(); boolean traverse[] = new boolean[n]; for (int i = 0; i < n; i++) traverse[i] = false; for (int i = 0; i < n; i++) { if (!traverse[i]) topSort(i, traverse, s); } while (!s.isEmpty()) { System.out.print(((int) s.peek() + 1) + " "); s.pop(); } System.out.println(); }
public void startMessage() { if (stack.isEmpty()) { stack.push(MimeMessage.this); } else { expect(Part.class); try { MimeMessage m = new MimeMessage(); ((Part) stack.peek()).setBody(m); stack.push(m); } catch (MessagingException me) { throw new Error(me); } } }
public void startMedia(SACMediaList media) throws CSSException { // Create the media rule and add it to the rule list CSSMediaRuleImpl mr = new CSSMediaRuleImpl(_parentStyleSheet, null, new MediaListImpl(media)); if (!_nodeStack.empty()) { ((CSSRuleListImpl) _nodeStack.peek()).add(mr); } // Create the rule list CSSRuleListImpl rules = new CSSRuleListImpl(); mr.setRuleList(rules); _nodeStack.push(mr); _nodeStack.push(rules); }
public void startFontFace() throws CSSException { // Create the font face rule and add it to the rule list CSSFontFaceRuleImpl ffr = new CSSFontFaceRuleImpl(_parentStyleSheet, null); if (!_nodeStack.empty()) { ((CSSRuleListImpl) _nodeStack.peek()).add(ffr); } // Create the style declaration CSSStyleDeclarationImpl decl = new CSSStyleDeclarationImpl(ffr); ffr.setStyle(decl); _nodeStack.push(ffr); _nodeStack.push(decl); }
public void startSelector(SelectorList selectors) throws CSSException { // Create the style rule and add it to the rule list CSSStyleRuleImpl sr = new CSSStyleRuleImpl(_parentStyleSheet, null, selectors); if (!_nodeStack.empty()) { ((CSSRuleListImpl) _nodeStack.peek()).add(sr); } // Create the style declaration CSSStyleDeclarationImpl decl = new CSSStyleDeclarationImpl(sr); sr.setStyle(decl); _nodeStack.push(sr); _nodeStack.push(decl); }
/** * Calculates the length of the the sub-path in a _transition path, that is used only by a given * string. * * @param str a String corresponding to a _transition path from sourceNode * @return an int denoting the size of the sub-path in the _transition path corresponding to * {@code str} that is only used by {@code str} */ private int calculateSoleTransitionPathLength(String str) { Stack<MDAGNode> transitionPathNodeStack = sourceNode.getTransitionPathNodes(str); transitionPathNodeStack.pop(); // The MDAGNode at the top of the stack is not needed // (we are processing the outgoing transitions of nodes inside str's _transition path, // the outgoing transitions of the MDAGNode at the top of the stack are outside this path) transitionPathNodeStack.trimToSize(); // Process each node in transitionPathNodeStack, using each to determine whether the // _transition path corresponding to str is only used by str. This is true if and only if // each node in the _transition path has a single outgoing _transition and is not an accept // state. while (!transitionPathNodeStack.isEmpty()) { MDAGNode currentNode = transitionPathNodeStack.peek(); if (currentNode.getOutgoingTransitions().size() <= 1 && !currentNode.isAcceptNode()) transitionPathNodeStack.pop(); else break; } ///// return (transitionPathNodeStack.capacity() - transitionPathNodeStack.size()); }
/** * Pops the output list currently at the top of the output list stack and appends it to the end of * the output list immediately underneath. * * @throws EmptyStackException if there is currently only one output list on the stack. * @see #mergeOutputList(List) */ public synchronized void mergeOutputList() { logger.debug3("Merging"); List oldTop = (List) listStack.pop(); List newTop = (List) listStack.peek(); newTop.addAll(oldTop); }
/** * Pops the output list currently at the top of the output list stack and discards it, and appends * the given replacement list to the output list immediately underneath. * * @param replacement A list of tokens to be appended to the output list currently immediately * under the top of the stack. * @throws EmptyStackException if there is currently only one output list on the stack. */ public synchronized void mergeOutputList(List replacement) { logger.debug3("Merging with replacement"); listStack.pop(); // discard result List newTop = (List) listStack.peek(); newTop.addAll(replacement); }
/** * Gets the output list currently at the top of the output list stack. * * @return The list of tokens currently at the top of the list stack. * @see #splitOutputList * @see #mergeOutputList() * @see #mergeOutputList(List) */ public synchronized List getOutputList() { return (List) listStack.peek(); }
public static JaxType parseType(String typeName, ClassDoc containingClass, JAXDoclet<?> doclet) throws InvalidJaxTypeException { typeName = typeName.trim(); char[] chars = typeName.toCharArray(); Stack<JaxType> types = new Stack<JaxType>(); JaxType currentType = new JaxType(); types.push(currentType); StringBuffer currentTypeName = new StringBuffer(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; log("Looking at char " + c); if (c == '<') { log("Start params for " + currentTypeName); // we're done for the type name setupType(currentType, currentTypeName, containingClass, doclet); // add a parameter to the current type JaxType parameterType = new JaxType(); currentType.parameters.add(parameterType); currentType = parameterType; // prepare for the parameter type types.push(currentType); } else if (c == '>') { // we're done for the parameter type if (currentTypeName.length() > 0) setupType(currentType, currentTypeName, containingClass, doclet); // reset and pop types.pop(); currentType = types.peek(); log("End params for " + currentType.typeName); // we should have at least the top type if (types.size() < 1) throw new InvalidJaxTypeException(); } else if (c == ',') { // we're done for the parameter type, unless it was already done by // closing its parameter list if (currentTypeName.length() > 0) { setupType(currentType, currentTypeName, containingClass, doclet); // reset, pop types.pop(); currentType = types.peek(); } log("Next params for " + currentType.typeName); // we should have at least the top type if (types.size() < 1) throw new InvalidJaxTypeException(); // add a parameter to the current type JaxType parameterType = new JaxType(); currentType.parameters.add(parameterType); currentType = parameterType; // prepare for the parameter type types.push(currentType); } else if (c == '[' || c == ']') { log("Dimension for " + currentType.typeName); // done for the class name unless it was already done by // closing its parameter list if (currentTypeName.length() > 0) { setupType(currentType, currentTypeName, containingClass, doclet); } // FIXME: check dimension correctness currentType.dimension += c; } else { log("Name char: " + currentTypeName); // if the currentType already has a name, barf if (currentType.typeName != null) throw new InvalidJaxTypeException(); currentTypeName.append(c); } } // perhaps we didn't have any parameters or dimension if (currentTypeName.length() > 0) { log("End of type without param or dimension for " + currentTypeName); setupType(currentType, currentTypeName, containingClass, doclet); } // we should have the original type to return if (types.size() != 1) throw new InvalidJaxTypeException(); return currentType; }
public char peekChar() { // precondition: assumes that there is something to pop return ((Character) stack.peek()).charValue(); }
static String getStmt(SamTokenizer f) throws TokenizerException { try { String asmCode = ""; Boolean returnFlag1; Boolean returnFlag2; switch (f.peekAtKind()) { case WORD: { String newWord = f.getWord(); switch (newWord) { case "return": { asmCode += getExp(f); myCheck(f, ';'); // SaM code for return. asmCode += "STOREOFF -" + Integer.toString(params.size() + 1) + "\n" + "ADDSP -" + Integer.toString(varCounter - 2) + "\n" + "JUMPIND\n"; returnFlags.push(true); return asmCode; } case "if": { // Generate two valid lables for divergence. String label1 = getLabel(); String label2 = getLabel(); myCheck(f, '('); asmCode += getExp(f); myCheck(f, ')'); asmCode += ("JUMPC " + label1 + "\n"); // Buffer the statements for if condition. String tempString = getStmt(f); returnFlag1 = returnFlags.pop(); myCheck(f, "else"); asmCode += getStmt(f); returnFlag2 = returnFlags.pop(); // Manage the divergence. asmCode += ("JUMP " + label2 + "\n" + label1 + ":\n" + tempString + label2 + ":\n"); if (returnFlag1 && returnFlag2) returnFlags.push(true); else returnFlags.push(false); return asmCode; } case "while": { String label1 = getLabel(); String label2 = getLabel(); // Push the label as the return position. labels.push(label2); myCheck(f, '('); asmCode += (label1 + ":\n"); asmCode += getExp(f); asmCode += ("ISNIL\n" + "JUMPC " + label2 + "\n"); myCheck(f, ')'); // Flag indicating that we are in a while loop (possibly nested while loops.) flags.push(true); asmCode += getStmt(f); asmCode += ("JUMP " + label1 + "\n" + label2 + ":\n"); // Once finish parsing the while loop, pop out the labels and flags. labels.pop(); flags.pop(); return asmCode; } case "break": { // flags.empty() indicates that we are not currently in a while loop. if (flags.empty()) throw new TokenizerException("Error: Invalid break statement."); myCheck(f, ';'); returnFlags.push(false); // Jump to the current inner most return postion. return "JUMP " + labels.peek() + "\n"; } default: // Assign statement // Check if the variable is already defined. if (!symTables.lastElement().containsKey(newWord)) throw new TokenizerException("Error: Variable not declared."); myCheck(f, '='); asmCode += getExp(f); myCheck(f, ';'); // Get the address of the variable from the symbol table. int addr = symTables.lastElement().get(newWord); asmCode += ("STOREOFF " + Integer.toString(addr) + "\n"); returnFlags.push(false); return asmCode; } } case OPERATOR: { switch (f.getOp()) { case '{': { asmCode += getBlock(f); return asmCode; } case ';': returnFlags.push(false); return asmCode; default: throw new TokenizerException("Error: Invalid operator inside a statement."); } } default: throw new TokenizerException("Error: Invalid Statement."); } } catch (Exception e) { System.out.println(e.getMessage()); throw new TokenizerException("Error: Invalid Statement."); } }
public void property(String name, LexicalUnit value, boolean important) throws CSSException { CSSStyleDeclarationImpl decl = (CSSStyleDeclarationImpl) _nodeStack.peek(); decl.addProperty(new Property(name, new CSSValueImpl(value), important)); }