Ejemplo n.º 1
0
  private void dfs(Digraph G, int v) {
    marked[v] = true;
    preorder[v] = pre++;
    stack1.push(v);
    stack2.push(v);
    for (int w : G.adj(v)) {
      if (!marked[w]) dfs(G, w);
      else if (id[w] == -1) {
        while (preorder[stack2.peek()] > preorder[w]) stack2.pop();
      }
    }

    // found strong component containing v
    if (stack2.peek() == v) {
      stack2.pop();
      int w;
      do {
        w = stack1.pop();
        id[w] = count;
      } while (w != v);
      count++;
    }
  }
Ejemplo n.º 2
0
  /**
   * Reads a sequence of transactions from standard input; takes a command-line integer M; prints to
   * standard output the M largest transactions in descending order.
   */
  public static void main(String[] args) {
    int M = Integer.parseInt(args[0]);
    MinPQ<Transaction> pq = new MinPQ<Transaction>(M + 1);

    while (StdIn.hasNextLine()) {
      // Create an entry from the next line and put on the PQ.
      String line = StdIn.readLine();
      Transaction transaction = new Transaction(line);
      pq.insert(transaction);

      // remove minimum if M+1 entries on the PQ
      if (pq.size() > M) pq.delMin();
    } // top M entries are on the PQ

    // print entries on PQ in reverse order
    Stack<Transaction> stack = new Stack<Transaction>();
    for (Transaction transaction : pq) stack.push(transaction);
    for (Transaction transaction : stack) StdOut.println(transaction);
  }
Ejemplo n.º 3
0
 /**
  * Returns the vertices in reverse postorder.
  *
  * @return the vertices in reverse postorder, as an iterable of vertices
  */
 public Iterable<Integer> reversePost() {
   Stack<Integer> reverse = new Stack<Integer>();
   for (int v : postorder) reverse.push(v);
   return reverse;
 }