/** * Method to find the Euler Tour based on the Hierholzer's algorithm. * * @param g : Input graph for which the tour is to be found. * @return : Returns a list of edges that comprises of the Euler Tour. */ public static List<Edge> findEulerTour(Graph<Vertex> g) { Vertex start = g.verts.get(1); Stack<Edge> forward = new Stack<Edge>(); Stack<Edge> backtrack = new Stack<Edge>(); Edge e = getUnvisitedEdge(start); while (e != null) { e.visited = true; forward.push(e); e = getUnvisitedEdge(e.To); } while (!(forward.isEmpty())) { e = forward.pop(); backtrack.push(e); e = getUnvisitedEdge(e.From); while (e != null) { e.visited = true; forward.push(e); e = getUnvisitedEdge(e.To); } } List<Edge> path = new LinkedList<Edge>(); while (!backtrack.isEmpty()) { Edge edge = backtrack.pop(); path.add(edge); } return path; }
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(); }
private CellSet seedFillOld(Cell seed, char newChar) { CellSet cellsFilled = new CellSet(); char oldChar = get(seed); if (oldChar == newChar) return cellsFilled; if (isOutOfBounds(seed)) return cellsFilled; Stack<Cell> stack = new Stack<Cell>(); stack.push(seed); while (!stack.isEmpty()) { Cell cell = stack.pop(); set(cell, newChar); cellsFilled.add(cell); Cell nCell = cell.getNorth(); Cell sCell = cell.getSouth(); Cell eCell = cell.getEast(); Cell wCell = cell.getWest(); if (get(nCell) == oldChar) stack.push(nCell); if (get(sCell) == oldChar) stack.push(sCell); if (get(eCell) == oldChar) stack.push(eCell); if (get(wCell) == oldChar) stack.push(wCell); } return cellsFilled; }
public static void createNgramsFromFolder( File input_folder, File output_folder, int ngram_value) { Stack<File> stack = new Stack<File>(); stack.push(input_folder); while (!stack.isEmpty()) { File child = stack.pop(); if (child.isDirectory()) { for (File f : child.listFiles()) stack.push(f); } else if (child.isFile()) { try { System.out.println("Processing: " + child.getAbsolutePath()); FileReader fr = new FileReader(child.getAbsolutePath()); FileWriter outputFile = new FileWriter(output_folder + "/file" + file_no); BufferedReader br = new BufferedReader(fr); String readline = ""; while ((readline = br.readLine()) != null) { String[] words = readline.split("\\s+"); for (int i = 0; i < words.length - ngram_value + 1; i++) { String ngram = ""; for (int j = 0; j < ngram_value; j++) ngram = ngram + " " + words[i + j]; outputFile.write(ngram + "\n"); } } file_no++; outputFile.close(); br.close(); fr.close(); } catch (Exception e) { System.out.println("File not found:" + e); } } } }
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; } } }
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 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); } } }
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(); }
int store(BytecodeBuffer b, int start, int end) { ByteArray a = wrappers.isEmpty() ? null : (ByteArray) wrappers.pop(); if (a == null) { a = newByteArray(); } a.clear(); a.b = b; a.start = start; a.end = end; a.init(); Integer index = IntegerPool.getNumber(map.size() + 1); map.put(a, index); return index.intValue(); }
/** * 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()); }
public LinkedList<DirEdge> getFlowPath() { // do a depth first search to see if there is path from source to the sink boolean[] visited = new boolean[v]; Arrays.fill(visited, false); Stack<Integer> tobeVisited = new Stack<Integer>(); tobeVisited.push(source); int[] predecessor = new int[v]; Arrays.fill(predecessor, -1); while (!tobeVisited.isEmpty()) { int vertex = tobeVisited.pop(); if (!visited[vertex]) { // System.out.println("Visiting " + vertex); visited[vertex] = true; // put vertex's next hop nodes into the stack ListIterator it = edges.get(vertex).listIterator(); while (it.hasNext()) { DirEdge e = (DirEdge) it.next(); if (predecessor[e.end] == -1) { predecessor[e.end] = vertex; } if (e.end == sink) { return constructPath(predecessor); } if (!visited[e.end]) { tobeVisited.push(e.end); } } } } return null; // we cannot find an augment path }
/** * Locates and returns the '*' boundaries that we would encounter if we did a flood-fill at <code> * seed</code>. */ public CellSet findBoundariesExpandingFrom(Cell seed) { CellSet boundaries = new CellSet(); char oldChar = get(seed); if (isOutOfBounds(seed)) return boundaries; char newChar = 1; // TODO: kludge Stack<Cell> stack = new Stack<Cell>(); stack.push(seed); while (!stack.isEmpty()) { Cell cell = stack.pop(); set(cell, newChar); Cell nCell = cell.getNorth(); Cell sCell = cell.getSouth(); Cell eCell = cell.getEast(); Cell wCell = cell.getWest(); if (get(nCell) == oldChar) stack.push(nCell); else if (get(nCell) == '*') boundaries.add(nCell); if (get(sCell) == oldChar) stack.push(sCell); else if (get(sCell) == '*') boundaries.add(sCell); if (get(eCell) == oldChar) stack.push(eCell); else if (get(eCell) == '*') boundaries.add(eCell); if (get(wCell) == oldChar) stack.push(wCell); else if (get(wCell) == '*') boundaries.add(wCell); } return boundaries; }
private void endTag() { if (!finalPass) return; String tagName = scan.getToken().trim(); String ns = scan.getNamespace(); if (tagMetaStack.isEmpty()) throw new GrailsTagException( "Found closing Grails tag with no opening [" + tagName + "]", pageName, getCurrentOutputLineNumber()); TagMeta tm = tagMetaStack.pop(); String lastInStack = tm.name; String lastNamespaceInStack = tm.namespace; // if the tag name is blank then it has been closed by the start tag ie <tag /> if (GrailsStringUtils.isBlank(tagName)) { tagName = lastInStack; } if (!lastInStack.equals(tagName) || !lastNamespaceInStack.equals(ns)) { throw new GrailsTagException( "Grails tag [" + lastNamespaceInStack + ":" + lastInStack + "] was not closed", pageName, getCurrentOutputLineNumber()); } if (GroovyPage.DEFAULT_NAMESPACE.equals(ns) && tagRegistry.isSyntaxTag(tagName)) { if (tm.instance instanceof GroovySyntaxTag) { GroovySyntaxTag tag = (GroovySyntaxTag) tm.instance; tag.doEndTag(); } else { throw new GrailsTagException( "Grails tag [" + tagName + "] was not closed", pageName, getCurrentOutputLineNumber()); } } else { int bodyTagIndex = -1; if (!tm.emptyTag && !tm.bufferMode) { bodyTagIndex = tagIndex; out.println("})"); closureLevel--; } if (tm.bufferMode && tm.bufferPartNumber != -1) { if (!bodyVarsDefined.contains(tm.tagIndex)) { // out.print("def "); bodyVarsDefined.add(tm.tagIndex); } out.println("createClosureForHtmlPart(" + tm.bufferPartNumber + ", " + tm.tagIndex + ")"); bodyTagIndex = tm.tagIndex; tm.bufferMode = false; } if (jspTags.containsKey(ns)) { String uri = jspTags.get(ns); out.println("jspTag = getJspTag('" + uri + "', '" + tagName + "')"); out.println( "if (!jspTag) throw new GrailsTagException('Unknown JSP tag " + ns + ":" + tagName + "')"); out.print("jspTag.doTag(out," + attrsVarsMapDefinition.get(tagIndex) + ","); if (bodyTagIndex > -1) { out.print("getBodyClosure(" + bodyTagIndex + ")"); } else { out.print("null"); } out.println(")"); } else { if (tm.hasAttributes) { out.println( "invokeTag('" + tagName + "','" + ns + "'," + getCurrentOutputLineNumber() + "," + attrsVarsMapDefinition.get(tagIndex) + "," + bodyTagIndex + ")"); } else { out.println( "invokeTag('" + tagName + "','" + ns + "'," + getCurrentOutputLineNumber() + ",[:]," + bodyTagIndex + ")"); } } } tm.bufferMode = false; tagIndex--; }
private void page() { LOG.debug("parse: page"); if (finalPass) { out.println(); if (pluginAnnotation != null) { out.println(pluginAnnotation); } out.print("class "); out.print(className); out.println(" extends GroovyPage {"); out.println( "public String getGroovyPageFileName() { \"" + pageName.replaceAll("\\\\", "/") + "\" }"); out.println("public Object run() {"); /* out.println("def params = binding.params"); out.println("def request = binding.request"); out.println("def flash = binding.flash"); out.println("def response = binding.response"); */ out.println("Writer " + GroovyPage.OUT + " = getOut()"); out.println("Writer " + GroovyPage.EXPRESSION_OUT + " = getExpressionOut()"); // out.println("JspTagLib jspTag"); if (sitemeshPreprocessMode) { out.println("registerSitemeshPreprocessMode()"); } } loop: for (; ; ) { if (doNextScan) { state = scan.nextToken(); } else { doNextScan = true; } // Flush any buffered whitespace if there's not a possibility of more whitespace // or a new tag which will handle flushing as necessary if ((state != GSTART_TAG) && (state != HTML)) { flushBufferedWhiteSpace(); previousContentWasNonWhitespace = false; // well, we don't know } switch (state) { case EOF: break loop; case HTML: html(); break; case JEXPR: scriptletExpr(); break; case JSCRIPT: script(false); break; case JDIRECT: direct(); break; case JDECLAR: declare(false); break; case GEXPR: expr(); break; case GSCRIPT: script(true); break; case GDIRECT: direct(); break; case GDECLAR: declare(true); break; case GSTART_TAG: startTag(); break; case GEND_EMPTY_TAG: case GEND_TAG: endTag(); break; } } if (finalPass) { if (!tagMetaStack.isEmpty()) { throw new GrailsTagException( "Grails tags were not closed! [" + tagMetaStack + "] in GSP " + pageName + "", pageName, getCurrentOutputLineNumber()); } out.println("}"); out.println("public static final Map " + CONSTANT_NAME_JSP_TAGS + " = new HashMap()"); if (jspTags != null && jspTags.size() > 0) { out.println("static {"); for (Map.Entry<String, String> entry : jspTags.entrySet()) { out.print("\t" + CONSTANT_NAME_JSP_TAGS + ".put('"); out.print(escapeGroovy(entry.getKey())); out.print("','"); out.print(escapeGroovy(entry.getValue())); out.println("')"); } out.println("}"); } out.println("protected void init() {"); out.println("\tthis.jspTags = " + CONSTANT_NAME_JSP_TAGS); out.println("}"); out.println( "public static final String " + CONSTANT_NAME_CONTENT_TYPE + " = '" + escapeGroovy(contentType) + "'"); out.println( "public static final long " + CONSTANT_NAME_LAST_MODIFIED + " = " + lastModified + "L"); out.println( "public static final String " + CONSTANT_NAME_EXPRESSION_CODEC + " = '" + escapeGroovy(expressionCodecDirectiveValue) + "'"); out.println( "public static final String " + CONSTANT_NAME_STATIC_CODEC + " = '" + escapeGroovy(staticCodecDirectiveValue) + "'"); out.println( "public static final String " + CONSTANT_NAME_OUT_CODEC + " = '" + escapeGroovy(outCodecDirectiveValue) + "'"); out.println( "public static final String " + CONSTANT_NAME_TAGLIB_CODEC + " = '" + escapeGroovy(taglibCodecDirectiveValue) + "'"); out.println("}"); if (shouldAddLineNumbers()) { addLineNumbers(); } } else { for (int i = 0; i < DEFAULT_IMPORTS.length; i++) { out.print("import "); out.println(DEFAULT_IMPORTS[i]); } } }
/** Delete the dst files/dirs which do not exist in src */ private static void deleteNonexisting( FileSystem dstfs, FileStatus dstroot, Path dstsorted, FileSystem jobfs, Path jobdir, JobConf jobconf, Configuration conf) throws IOException { if (!dstroot.isDir()) { throw new IOException( "dst must be a directory when option " + Options.DELETE.cmd + " is set, but dst (= " + dstroot.getPath() + ") is not a directory."); } // write dst lsr results final Path dstlsr = new Path(jobdir, "_distcp_dst_lsr"); final SequenceFile.Writer writer = SequenceFile.createWriter( jobfs, jobconf, dstlsr, Text.class, FileStatus.class, SequenceFile.CompressionType.NONE); try { // do lsr to get all file statuses in dstroot final Stack<FileStatus> lsrstack = new Stack<FileStatus>(); for (lsrstack.push(dstroot); !lsrstack.isEmpty(); ) { final FileStatus status = lsrstack.pop(); if (status.isDir()) { for (FileStatus child : dstfs.listStatus(status.getPath())) { String relative = makeRelative(dstroot.getPath(), child.getPath()); writer.append(new Text(relative), child); lsrstack.push(child); } } } } finally { checkAndClose(writer); } // sort lsr results final Path sortedlsr = new Path(jobdir, "_distcp_dst_lsr_sorted"); SequenceFile.Sorter sorter = new SequenceFile.Sorter( jobfs, new Text.Comparator(), Text.class, FileStatus.class, jobconf); sorter.sort(dstlsr, sortedlsr); // compare lsr list and dst list SequenceFile.Reader lsrin = null; SequenceFile.Reader dstin = null; try { lsrin = new SequenceFile.Reader(jobfs, sortedlsr, jobconf); dstin = new SequenceFile.Reader(jobfs, dstsorted, jobconf); // compare sorted lsr list and sorted dst list final Text lsrpath = new Text(); final FileStatus lsrstatus = new FileStatus(); final Text dstpath = new Text(); final Text dstfrom = new Text(); final FsShell shell = new FsShell(conf); final String[] shellargs = {"-rmr", null}; boolean hasnext = dstin.next(dstpath, dstfrom); for (; lsrin.next(lsrpath, lsrstatus); ) { int dst_cmp_lsr = dstpath.compareTo(lsrpath); for (; hasnext && dst_cmp_lsr < 0; ) { hasnext = dstin.next(dstpath, dstfrom); dst_cmp_lsr = dstpath.compareTo(lsrpath); } if (dst_cmp_lsr == 0) { // lsrpath exists in dst, skip it hasnext = dstin.next(dstpath, dstfrom); } else { // lsrpath does not exist, delete it String s = new Path(dstroot.getPath(), lsrpath.toString()).toString(); if (shellargs[1] == null || !isAncestorPath(shellargs[1], s)) { shellargs[1] = s; int r = 0; try { r = shell.run(shellargs); } catch (Exception e) { throw new IOException("Exception from shell.", e); } if (r != 0) { throw new IOException( "\"" + shellargs[0] + " " + shellargs[1] + "\" returns non-zero value " + r); } } } } } finally { checkAndClose(lsrin); checkAndClose(dstin); } }