Ejemplo n.º 1
1
  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();
  }
Ejemplo n.º 2
0
  public static void main(String[] args) throws Exception {
    int V, E, s, a, b, w;

    File f = new File("in_06.txt");
    Scanner sc = new Scanner(f);

    V = sc.nextInt();
    E = sc.nextInt();
    s = sc.nextInt();

    AdjList.clear();
    for (int i = 0; i < V; i++) {
      Vector<IntegerPair> Neighbor = new Vector<IntegerPair>();
      AdjList.add(Neighbor); // add neighbor list to Adjacency List
    }

    for (int i = 0; i < E; i++) {
      a = sc.nextInt();
      b = sc.nextInt();
      w = sc.nextInt();
      AdjList.get(a).add(new IntegerPair(b, w)); // first time using weight
    }

    // as an example, we start from this source (see Figure 1.15)
    Vector<Integer> dist = new Vector<Integer>();
    dist.addAll(Collections.nCopies(V, INF));
    dist.set(s, 0);

    // Bellman Ford routine
    for (int i = 0; i < V - 1; i++) // relax all E edges V-1 times, O(V)
    for (int u = 0; u < V; u++) { // these two loops = O(E)
        Iterator it = AdjList.get(u).iterator();
        while (it.hasNext()) { // relax these edges
          IntegerPair v = (IntegerPair) it.next();
          dist.set(v.first(), Math.min(dist.get(v.first()), dist.get(u) + v.second()));
        }
      }

    boolean negative_cycle_exist = false;
    for (int u = 0; u < V; u++) { // one more pass to check
      Iterator it = AdjList.get(u).iterator();
      while (it.hasNext()) { // relax these edges
        IntegerPair v = (IntegerPair) it.next();
        if (dist.get(v.first()) > dist.get(u) + v.second()) // should be false, but if possible
        negative_cycle_exist = true; // then negative cycle exists!
      }
    }
    System.out.printf("Negative Cycle Exist? %s\n", negative_cycle_exist ? "Yes" : "No");

    if (!negative_cycle_exist)
      for (int i = 0; i < V; i++) System.out.printf("SSSP(%d, %d) = %d\n", s, i, dist.get(i));
  }
Ejemplo n.º 3
0
 Woman ExtractMax() {
   Woman maxV = A.get(1);
   A.set(1, A.get(BinaryHeapSize));
   BinaryHeapSize--; // virtual decrease
   shiftDown(1);
   return maxV;
 }
Ejemplo n.º 4
0
  void shiftUp(int i) {
    Woman temp = A.get(i);
    Woman temp2;
    temp.index = i;
    while (i > 1 && A.get(parent(i)).dilation <= A.get(i).dilation) {
      if (A.get(parent(i)).dilation == A.get(i).dilation
          && A.get(parent(i)).order < A.get(i).order) {
        break;
      }

      temp = A.get(i);
      temp2 = A.get(parent(i));
      temp.index = parent(i);
      temp2.index = i;
      A.set(i, temp2);
      A.set(parent(i), temp);
      i = parent(i);
    }
  }
Ejemplo n.º 5
0
 void Update(Woman mother) {
   Woman temp;
   int i = getNameIndex(mother.name);
   temp = A.get(i);
   temp.dilation = A.get(i).dilation + mother.dilation;
   temp.name = A.get(i).name;
   temp.order = A.get(i).order;
   A.set(i, temp);
   shiftUp(i);
   shiftDown(i);
 }
Ejemplo n.º 6
0
 void Insert(Woman mother) {
   BinaryHeapSize++;
   binaryHeapOrder++;
   mother.order = binaryHeapOrder;
   B.put(mother.name, mother);
   if (BinaryHeapSize >= A.size()) {
     A.add(mother);
   } else {
     A.set(BinaryHeapSize, mother);
   }
   shiftUp(BinaryHeapSize);
 }
Ejemplo n.º 7
0
  void Delete(String motherName) {
    int i = getNameIndex(motherName);
    A.set(i, A.get(BinaryHeapSize));
    A.remove(BinaryHeapSize);
    B.remove(motherName);

    BinaryHeapSize--;

    if ((i - 1) != BinaryHeapSize) {
      shiftUp(i);
      shiftDown(i);
    }
  }
Ejemplo n.º 8
0
  public static void main(String[] args) throws Exception {
    /*
    // Graph in Figure 4.3, format: list of unweighted edges
    // This example shows another form of reading graph input
    13 16
    0 1    1 2    2  3   0  4   1  5   2  6    3  7   5  6
    4 8    8 9    5 10   6 11   7 12   9 10   10 11  11 12
    */

    File f = new File("in_04.txt");
    Scanner sc = new Scanner(f);

    V = sc.nextInt();
    E = sc.nextInt();

    AdjList.clear();
    for (int i = 0; i < V; i++) {
      Vector<IntegerPair> Neighbor = new Vector<IntegerPair>();
      AdjList.add(Neighbor); // add neighbor list to Adjacency List
    }

    for (int i = 0; i < E; i++) {
      a = sc.nextInt();
      b = sc.nextInt();
      AdjList.get(a).add(new IntegerPair(b, 0));
      AdjList.get(b).add(new IntegerPair(a, 0));
    }

    // as an example, we start from this source, see Figure 4.3
    s = 5;

    // BFS routine
    // inside void main(String[] args) -- we do not use recursion, thus we do not need to create
    // separate function!
    Vector<Integer> dist = new Vector<Integer>();
    dist.addAll(Collections.nCopies(V, 1000000000));
    dist.set(s, 0); // start from source
    Queue<Integer> q = new LinkedList<Integer>();
    q.offer(s);
    p.clear();
    p.addAll(
        Collections.nCopies(V, -1)); // to store parent information (p must be a global variable!)
    int layer = -1; // for our output printing purpose
    Boolean isBipartite = true;

    while (!q.isEmpty()) {
      int u = q.poll(); // queue: layer by layer!
      if (dist.get(u) != layer) System.out.printf("\nLayer %d:", dist.get(u));
      layer = dist.get(u);
      System.out.printf(", visit %d", u);
      Iterator it = AdjList.get(u).iterator();
      while (it.hasNext()) { // for each neighbours of u
        IntegerPair v = (IntegerPair) it.next();
        if (dist.get(v.first()) == 1000000000) { // if v not visited before
          dist.set(v.first(), dist.get(u) + 1); // then v is reachable from u
          q.offer(v.first()); // enqueue v for next steps
          p.set(v.first(), u); // parent of v is u
        } else if ((dist.get(v.first()) % 2) == (dist.get(u) % 2)) // same parity
        isBipartite = false;
      }
    }

    System.out.printf("\nShortest path: ");
    printpath(7);
    System.out.printf("\n");
    System.out.printf("isBipartite? %d\n", isBipartite ? 1 : 0);
  }
Ejemplo n.º 9
0
  /**
   * ************************************************************************ * * Method: performSet
   * * Input: CMIRequest theRequest - tokenized LMSSetValue() request * DMErrorManager dmErroMgr -
   * Error Manager * Output: none * * Description: This method takes the necessary steps to process
   * * an LMSSetValue() request *
   * *************************************************************************
   */
  public void performSet(CMIRequest theRequest, DMErrorManager dmErrorMgr) {
    if (true) {
      System.out.println("CMIObjectives::performSet()");
    }

    // The next token must be an array.  If not throw
    // an exception for this request.
    int index = -1;

    // Get the next token off of the request
    String token = theRequest.getNextToken();

    if (true) {
      System.out.println("Token being processed: " + token);
    }

    // Check to see if next token is an array index.  For
    // a LMSSetValue() this is true
    try {
      // Try to convert the token to the index
      Integer tmpInt = new Integer(token);
      index = tmpInt.intValue();

      // Get the Objective Data at position of the index
      CMIObjectiveData tmpObj = (CMIObjectiveData) objectives.elementAt(index);

      // An objective existed at the given index.
      // Invoke the performSet() on the Objective Data
      tmpObj.performSet(theRequest, dmErrorMgr);

      // replace the old ObjectiveData with the newly set Objective
      // Data.
      objectives.set(index, tmpObj);
    } catch (NumberFormatException nfe) {
      if (theRequest.isAKeywordRequest() == true) {
        dmErrorMgr.recKeyWordError(token);
      } else {
        if (true) {
          // Invalid parameter passed to LMSSetValue()
          System.out.println("Error - Data Model Element not implemented");
          System.out.println(
              "Invalid data model element: "
                  + theRequest.getRequest()
                  + " passed to LMSSetValue()");
        }

        // Notify error manager
        dmErrorMgr.recNotImplementedError(theRequest);
      }
    } catch (ArrayIndexOutOfBoundsException e) {
      if (true) {
        System.out.println("First time setting the Objective Data");
      }

      if (index <= objectives.size()) {
        // A new Objective Data.
        CMIObjectiveData objData = new CMIObjectiveData();

        // Invoke performSet() on the new Objective Data
        objData.performSet(theRequest, dmErrorMgr);

        // Place the Objective data into the vector at the
        // index position
        objectives.add(index, objData);
      } else {
        dmErrorMgr.SetCurrentErrorCode("201");
      }
    }

    // Done processing.  Let CMIRequest object know the processing
    // of the LMSGetValue() is done.
    theRequest.done();

    return;
  } // end of performSet
Ejemplo n.º 10
0
 Vector<Woman> BinaryHeapSort(Woman[] array) {
   BuildBinaryHeap(array);
   int N = array.length;
   for (int i = 1; i <= N; i++) A.set(N - i + 1, ExtractMax());
   return A; // ignore the first index 0
 }
Ejemplo n.º 11
0
  void shiftDown(int i) {
    Woman temp = A.get(i);
    Woman temp2;
    temp.index = i;

    boolean isLeft = true;
    boolean isRight = true;

    while (i <= BinaryHeapSize) {
      isLeft = true;
      isRight = true;

      int leftMax = 0, leftMaxId = 0;
      int rightMax = 0, rightMaxId = 0;

      int maxV = A.get(i).dilation, max_id = i;
      if (left(i) <= BinaryHeapSize && maxV <= A.get(left(i)).dilation) {
        if (maxV == A.get(left(i)).dilation) {
          if (A.get(i).order < A.get(left(i)).order) isLeft = false;
        }
        if (isLeft) {
          leftMax = A.get(left(i)).dilation;
          leftMaxId = left(i);
        }
      }

      if (right(i) <= BinaryHeapSize && maxV <= A.get(right(i)).dilation) {
        if (maxV == A.get(right(i)).dilation) {
          if (A.get(i).order < A.get(right(i)).order) isRight = false;
        }
        if (isRight) {
          rightMax = A.get(right(i)).dilation;
          rightMaxId = right(i);
        }
      }

      if (rightMax > leftMax) {
        maxV = A.get(right(i)).dilation;
        max_id = right(i);
      } else if (rightMax < leftMax) {
        maxV = A.get(left(i)).dilation;
        max_id = left(i);
      } else if (rightMax == leftMax) {
        if (A.get(rightMaxId).order > A.get(leftMaxId).order) {
          maxV = A.get(left(i)).dilation;
          max_id = left(i);
        } else if (A.get(rightMaxId).order < A.get(leftMaxId).order) {
          maxV = A.get(right(i)).dilation;
          max_id = right(i);
        }
      }

      if (max_id != i) {
        temp = A.get(i);
        temp2 = A.get(max_id);
        temp.index = max_id;
        temp2.index = i;
        A.set(i, temp2);
        A.set(max_id, temp);
        i = max_id;
      } else break;
    }
  }
Ejemplo n.º 12
0
  /**
   * This method is called when a whole download file has been finished downloading. It updates main
   * application window and starts the decoding thread.
   *
   * @param dlFile The DownloadFile object that is finished
   */
  private void handleFinishedDlFile(final DownloadFile dlFile) {
    final String filename = dlFile.getFilename();
    logger.msg("File downloading finished: " + filename, MyLogger.SEV_INFO);

    // notify application that download has finished
    SwingUtilities.invokeLater(
        new Runnable() {
          public void run() {
            mainApp.fileDownloadFinished(filename);
            mainApp.setProgBarToDecoding(filename, dlFile.getSegCount());
          }
        });

    // create result vector
    Vector<byte[]> articleData = new Vector<byte[]>();
    Vector<RspHandler> rspHandlers = dlFileRspHandlerMap.get(dlFile);
    for (int i = 0; i < rspHandlers.size(); i++) {
      byte[] tmpArray = removeFirstLine(rspHandlers.get(i).getData(true));
      articleData.add(tmpArray);
      rspHandlers.set(i, null); // free some memory
    }

    // call garbage collector
    rspHandlers = null;
    dlFileRspHandlerMap.remove(dlFile);
    Runtime.getRuntime().gc();

    logger.msg(
        "First line(s) dump:\n" + HelloNzbToolkit.firstLineFromByteData(articleData.get(0), 2),
        MyLogger.SEV_DEBUG);

    // determine data encoding (yenc or UU)
    String encoding = null;
    boolean bHasData = false;
    for (int i = 0; i < articleData.size(); i++) {
      byte[] abyteHelp = articleData.get(i);
      if (abyteHelp.length > 0) {
        bHasData = true;
        if (bytesEqualsString(abyteHelp, "=ybegin")) {
          encoding = "yenc";
          break;
        } else if (bytesEqualsString(abyteHelp, "begin ")) {
          encoding = "uu";
          break;
        }
      }
    }
    if (encoding == null) {
      if (bHasData) {
        encoding = "yenc";
        logger.msg(
            "No suitable decoder (no data) found for downloaded file: "
                + dlFile.getFilename()
                + " -- Assuming yenc.",
            MyLogger.SEV_WARNING);
      } else {
        // too bad, no decoder found for this file :(
        logger.msg(
            "No suitable decoder found for downloaded file (no data): " + dlFile.getFilename(),
            MyLogger.SEV_ERROR);

        // update main application window
        SwingUtilities.invokeLater(
            new Runnable() {
              public void run() {
                mainApp.fileDecodingFinished(dlFile.getFilename());
              }
            });

        return;
      }
    }

    /*
     * // determine data encoding String encoding = null;
     * if(bytesEqualsString(articleData.get(0), "=ybegin")) encoding =
     * "yenc"; else if(bytesEqualsString(articleData.get(0), "begin "))
     * encoding = "uu"; else { // too bad, no decoder found for this file :(
     * logger.msg("No suitable decoder found for downloaded file: " +
     * dlFile.getFilename(), MyLogger.SEV_ERROR);
     *
     * // update main application window SwingUtilities.invokeLater(new
     * Runnable() { public void run() {
     * mainApp.fileDecodingFinished(dlFile.getFilename()); } } );
     *
     * return; }
     */

    // start data decoding background thread
    FileDecoder fileDecoder = new FileDecoder(mainApp, dlDir, dlFile, articleData, encoding);
    Thread t = new Thread(fileDecoder);
    t.start();
  }