예제 #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();
  }
예제 #2
0
 /**
  * Pools the specified <tt>RawPacket</tt> in order to avoid future allocations and to reduce the
  * effects of garbage collection.
  *
  * @param pkt the <tt>RawPacket</tt> to be offered to {@link #rawPacketPool}
  */
 private void poolRawPacket(RawPacket pkt) {
   pkt.setBuffer(null);
   pkt.setFlags(0);
   pkt.setLength(0);
   pkt.setOffset(0);
   rawPacketPool.offer(pkt);
 }
예제 #3
0
  int bfs(String[] terrain, int sr, int sc, int er, int ec) {
    Queue<Node> nodes = new PriorityQueue<Node>();
    boolean seen[][] = new boolean[n][m];

    nodes.offer(new Node(sr, sc, 0));

    while (nodes.size() > 0) {
      Node top = nodes.poll();
      int r = top.r;
      int c = top.c;
      int cost = top.cost;

      if (r == er && c == ec) {
        return cost;
      }
      if (seen[r][c]) {
        continue;
      }

      seen[r][c] = true;

      for (int i = 0; i < dx.length; i++) {
        int nr = r + dx[i];
        int nc = c + dy[i];

        if (0 <= nr && nr < n && 0 <= nc && nc < m) {
          char u = terrain[r].charAt(c);
          char v = terrain[nr].charAt(nc);

          if (u == 'X' || u == '$' || v == 'X' || v == '$') {
            nodes.offer(new Node(nr, nc, cost + 2));
          } else {
            int uval = u - '0';
            int vval = v - '0';
            int dv = Math.abs(uval - vval);

            if (dv <= 1) {
              nodes.offer(new Node(nr, nc, cost + (dv == 0 ? 1 : 3)));
            }
          }
        }
      }
    }

    return -1;
  }
예제 #4
0
  public double next(int val) {

    if (q.size() == this.max) {
      total -= q.poll();
    }

    q.offer(val);
    total += val;

    return (double) total / q.size();
  }
    // we don't care about the return value but care about it throwing exception
    public void runMayThrow() throws Exception {
      if (endpoints.isEmpty()) {
        differencingDone.signalAll();
        logger.info(
            "No neighbors to repair with for "
                + tablename
                + " on "
                + range
                + ": "
                + getName()
                + " completed.");
        return;
      }

      // Checking all nodes are live
      for (InetAddress endpoint : endpoints) {
        if (!FailureDetector.instance.isAlive(endpoint)) {
          differencingDone.signalAll();
          logger.info(
              "Could not proceed on repair because a neighbor ("
                  + endpoint
                  + ") is dead: "
                  + getName()
                  + " failed.");
          return;
        }
      }

      AntiEntropyService.instance.sessions.put(getName(), this);
      Gossiper.instance.register(this);
      FailureDetector.instance.registerFailureDetectionEventListener(this);
      try {
        // Create and queue a RepairJob for each column family
        for (String cfname : cfnames) {
          RepairJob job = new RepairJob(cfname);
          jobs.offer(job);
          activeJobs.put(cfname, job);
        }

        jobs.peek().sendTreeRequests();

        // block whatever thread started this session until all requests have been returned:
        // if this thread dies, the session will still complete in the background
        completed.await();
        if (exception != null) throw exception;
      } catch (InterruptedException e) {
        throw new RuntimeException(
            "Interrupted while waiting for repair: repair will continue in the background.");
      } finally {
        FailureDetector.instance.unregisterFailureDetectionEventListener(this);
        Gossiper.instance.unregister(this);
        AntiEntropyService.instance.sessions.remove(getName());
      }
    }
  /**
   * Adds a wrapper for delayed processing.
   *
   * @param wrapper Wrapper to add.
   */
  void delay(GridOptimizedWrapper wrapper) {
    if (wrappers == null) wrappers = new LinkedList<GridOptimizedWrapper>();

    // Add to FIFO queue.
    wrappers.offer(wrapper);
  }
예제 #7
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);
  }
    // we don't care about the return value but care about it throwing exception
    public void runMayThrow() throws Exception {
      logger.info(
          String.format(
              "[repair #%s] new session: will sync %s on range %s for %s.%s",
              getName(), repairedNodes(), range, tablename, Arrays.toString(cfnames)));

      if (endpoints.isEmpty()) {
        differencingDone.signalAll();
        logger.info(
            String.format(
                "[repair #%s] No neighbors to repair with on range %s: session completed",
                getName(), range));
        return;
      }

      // Checking all nodes are live
      for (InetAddress endpoint : endpoints) {
        if (!FailureDetector.instance.isAlive(endpoint)) {
          differencingDone.signalAll();
          logger.info(
              String.format(
                  "[repair #%s] Cannot proceed on repair because a neighbor (%s) is dead: session failed",
                  getName(), endpoint));
          return;
        }

        if (Gossiper.instance.getVersion(endpoint) < MessagingService.VERSION_11 && isSequential) {
          logger.info(
              String.format(
                  "[repair #%s] Cannot repair using snapshots as node %s is pre-1.1",
                  getName(), endpoint));
          return;
        }
      }

      AntiEntropyService.instance.sessions.put(getName(), this);
      Gossiper.instance.register(this);
      FailureDetector.instance.registerFailureDetectionEventListener(this);
      try {
        // Create and queue a RepairJob for each column family
        for (String cfname : cfnames) {
          RepairJob job = new RepairJob(cfname);
          jobs.offer(job);
          activeJobs.put(cfname, job);
        }

        jobs.peek().sendTreeRequests();

        // block whatever thread started this session until all requests have been returned:
        // if this thread dies, the session will still complete in the background
        completed.await();
        if (exception == null) {
          logger.info(String.format("[repair #%s] session completed successfully", getName()));
        } else {
          logger.error(
              String.format("[repair #%s] session completed with the following error", getName()),
              exception);
          throw exception;
        }
      } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted while waiting for repair.");
      } finally {
        // mark this session as terminated
        terminate();
        FailureDetector.instance.unregisterFailureDetectionEventListener(this);
        Gossiper.instance.unregister(this);
        AntiEntropyService.instance.sessions.remove(getName());
      }
    }
예제 #9
0
  /**
   * Enqueues wrapper for delayed processing.
   *
   * @param wrapper Wrapper to enqueue.
   */
  void delay(GridOptimizedWrapper wrapper) {
    if (wrappers == null) wrappers = new LinkedList<GridOptimizedWrapper>();

    wrappers.offer(wrapper);
  }
예제 #10
0
  public Main() {
    try {
      in = new BufferedReader(new InputStreamReader(System.in));
      // minimum distance from D to K
      int numCities = nextInt();
      int tradeRoutes = nextInt();
      int[][] adjacencyMatrix = new int[numCities][numCities];
      int[] minDistance = new int[numCities];
      Arrays.fill(minDistance, 100000000);
      // Arrays.fill(adjacencyMatrix, -1);

      // int [] pencilCosts = new int[
      Node[] cities = new Node[numCities];
      for (int x = 0; x < tradeRoutes; x++) {
        int cityA = nextInt() - 1;
        int cityB = nextInt() - 1;
        int cost = nextInt();

        if (cities[cityA] == null) cities[cityA] = new Node(cityA);
        if (cities[cityB] == null) cities[cityB] = new Node(cityB);
        adjacencyMatrix[cityA][cityB] = cost;
        adjacencyMatrix[cityB][cityA] = cost;

        // cities[cityA].routes.add(new Edge(cost, cities[cityB]));
        // cities[cityB].routes.add(new Edge(cost, cities[cityA]));
      }

      int numStores = nextInt();
      int[] pencilCosts = new int[numCities];
      Arrays.fill(pencilCosts, -1);
      for (int x = 0; x < numStores; x++) {
        int ID = nextInt() - 1;
        int cost = nextInt();
        pencilCosts[ID] = cost;
      }
      int destination = nextInt() - 1;
      // if (isGood[destination]){

      // }
      int minCost = 100000000;

      Queue<Node> Q = new LinkedList<Node>();
      // PriorityQueue<Node> Q = new PriorityQueue<Node>();
      minDistance[destination] = 0;
      // cities[destination].distance = 0;
      Q.offer(cities[destination]);
      while (!Q.isEmpty()) {
        Node temp = Q.poll();
        for (int x = 0; x < numCities; x++) {
          if (adjacencyMatrix[temp.ID][x] != 0
              && (minDistance[x] == 100000000
                  || minDistance[x] > minDistance[temp.ID] + adjacencyMatrix[temp.ID][x])) {
            minDistance[x] = minDistance[temp.ID] + adjacencyMatrix[temp.ID][x];
            if (pencilCosts[x] != -1 && minDistance[x] < minCost) {
              // System.out.println(minCost);
              minCost = Math.min(minDistance[x] + pencilCosts[x], minCost);
              Q.offer(cities[x]);
            } else {
              if (pencilCosts[x] == -1) { // why>
                Q.offer(cities[x]);
              }
            }
            // Q.offer(temp.routes.get(x).destination);
          }
        }
      }

      for (int x = 0; x < numCities; x++) {
        if (pencilCosts[x] != -1
            && pencilCosts[x] + minDistance[x] < minCost
            && minDistance[x] != 100000000) {
          minCost = minDistance[x] + pencilCosts[x];
        }
      }
      System.out.println(minCost);

    } catch (IOException e) {
      System.out.println("IO: General");
    }
  }
예제 #11
0
  /**
   * Listens for incoming datagrams, stores them for reading by the <tt>read</tt> method and
   * notifies the local <tt>transferHandler</tt> that there's data to be read.
   */
  public void run() {
    DatagramPacket p = new DatagramPacket(buffer, 0, PACKET_RECEIVE_BUFFER_LENGTH);

    while (!closed) {
      try {
        // http://code.google.com/p/android/issues/detail?id=24765
        if (OSUtils.IS_ANDROID) p.setLength(PACKET_RECEIVE_BUFFER_LENGTH);

        receivePacket(p);
      } catch (IOException e) {
        ioError = true;
        break;
      }

      /*
       * Do the DatagramPacketFilters accept the received DatagramPacket?
       */
      DatagramPacketFilter[] datagramPacketFilters = getDatagramPacketFilters();
      boolean accept;

      if (!enabled) accept = false;
      else if (datagramPacketFilters == null) accept = true;
      else {
        accept = true;
        for (int i = 0; i < datagramPacketFilters.length; i++) {
          try {
            if (!datagramPacketFilters[i].accept(p)) {
              accept = false;
              break;
            }
          } catch (Throwable t) {
            if (t instanceof ThreadDeath) throw (ThreadDeath) t;
          }
        }
      }

      if (accept) {
        RawPacket pkts[] = createRawPacket(p);

        for (int i = 0; i < pkts.length; i++) {
          RawPacket pkt = pkts[i];

          pkts[i] = null;

          if (pkt != null) {
            if (pkt.isInvalid()) {
              /*
               * Return pkt to the pool because it is invalid and,
               * consequently, will not be made available to
               * reading.
               */
              poolRawPacket(pkt);
            } else {
              RawPacket oldPkt;

              synchronized (pktSyncRoot) {
                oldPkt = this.pkt;
                this.pkt = pkt;
              }
              if (oldPkt != null) {
                /*
                 * Return oldPkt to the pool because it was made
                 * available to reading and it was not read.
                 */
                poolRawPacket(oldPkt);
              }

              if (videoRecorder != null) videoRecorder.recordData(pkt);

              if ((transferHandler != null) && !closed) {
                try {
                  transferHandler.transferData(this);
                } catch (Throwable t) {
                  /*
                   * XXX We cannot allow transferHandler to
                   * kill us.
                   */
                  if (t instanceof ThreadDeath) {
                    throw (ThreadDeath) t;
                  } else {
                    logger.warn("An RTP packet may have not been" + " fully handled.", t);
                  }
                }
              }
            }
          }
        }
        rawPacketArrayPool.offer(pkts);
      }
    }
  }