Example #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();
  }
 /**
  * The basic method for splitting off a clause of a tree. This modifies the tree in place.
  *
  * @param tree The tree to split a clause from.
  * @param toKeep The edge representing the clause to keep.
  */
 static void splitToChildOfEdge(SemanticGraph tree, SemanticGraphEdge toKeep) {
   Queue<IndexedWord> fringe = new LinkedList<>();
   List<IndexedWord> nodesToRemove = new ArrayList<>();
   // Find nodes to remove
   // (from the root)
   for (IndexedWord root : tree.getRoots()) {
     nodesToRemove.add(root);
     for (SemanticGraphEdge out : tree.outgoingEdgeIterable(root)) {
       if (!out.equals(toKeep)) {
         fringe.add(out.getDependent());
       }
     }
   }
   // (recursively)
   while (!fringe.isEmpty()) {
     IndexedWord node = fringe.poll();
     nodesToRemove.add(node);
     for (SemanticGraphEdge out : tree.outgoingEdgeIterable(node)) {
       if (!out.equals(toKeep)) {
         fringe.add(out.getDependent());
       }
     }
   }
   // Remove nodes
   nodesToRemove.forEach(tree::removeVertex);
   // Set new root
   tree.setRoot(toKeep.getDependent());
 }
Example #3
0
  private static PencilPosition findShortestRoute(int[][] maze) {
    // all found solutions to the maze
    PriorityQueue<PencilPosition> solutions =
        new PriorityQueue<PencilPosition>(5, new PencilPositionComparator());
    // bread-first search queue
    Queue<PencilPosition> routes = new LinkedList<PencilPosition>();
    // set of already visited positions
    Set<PencilPosition> visitedPositions = new HashSet<PencilPosition>();

    // add the starting positions, which is always (0,0)
    routes.add(new PencilPosition(0, 0, false, null));

    while (!routes.isEmpty()) {
      PencilPosition position = routes.poll();

      // if this is the destinations position then we've found a solution
      if (0 == maze[position.row][position.column]) {
        solutions.add(position);
        continue;
      }

      // if we haven't already visited this position
      if (!visitedPositions.contains(position)) {
        routes.addAll(findPossibleRoutes(position, maze));
        visitedPositions.add(position);
      }
    }

    return solutions.poll();
  }
Example #4
0
 /**
  * This method is used to embed syntaxes associated with UDT attribute notations to a queue of
  * string tokens extracted from a UDT parameter.
  *
  * @param tokens Queue of string tokens
  * @param syntaxQueue Syntax embedded tokens
  * @param isIndex Flag to determine whether a particular string token is an inidex or a column
  *     name
  */
 public static void getSyntaxEmbeddedQueue(
     Queue<String> tokens, Queue<String> syntaxQueue, boolean isIndex) {
   if (!tokens.isEmpty()) {
     if ("[".equals(tokens.peek())) {
       isIndex = true;
       tokens.poll();
       syntaxQueue.add("INEDX_START");
       syntaxQueue.add(tokens.poll());
     } else if ("]".equals(tokens.peek())) {
       isIndex = false;
       tokens.poll();
       syntaxQueue.add("INDEX_END");
     } else if (".".equals(tokens.peek())) {
       tokens.poll();
       syntaxQueue.add("DOT");
       syntaxQueue.add("COLUMN");
       syntaxQueue.add(tokens.poll());
     } else {
       if (isIndex) {
         syntaxQueue.add("INDEX");
         syntaxQueue.add(tokens.poll());
       } else {
         syntaxQueue.add("COLUMN");
         syntaxQueue.add(tokens.poll());
       }
     }
     getSyntaxEmbeddedQueue(tokens, syntaxQueue, isIndex);
   }
 }
  @Override
  public Boolean call() throws Exception {

    long timeoutMillis = 5000;

    try {
      getServersFile();
      getZkRunning();

      while (true) {
        while (!restartQueue.isEmpty()) {
          LOG.debug("Restart queue size [" + restartQueue.size() + "]");
          RestartHandler handler = restartQueue.poll();
          Future<ScriptContext> runner = pool.submit(handler);
          ScriptContext scriptContext = runner.get(); // blocking call
          if (scriptContext.getExitCode() != 0) restartQueue.add(handler);
        }

        try {
          Thread.sleep(timeoutMillis);
        } catch (InterruptedException e) {
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
      LOG.error(e);
      pool.shutdown();
      throw e;
    }
  }
Example #6
0
  /* Fill the bipartite graph if possible. */
  boolean[] solve() {
    Map<Integer, List<Integer>> gr = makeGraph();

    boolean[] truthTable = new boolean[count];
    // keep track of which ones we've visited
    boolean[] visited = new boolean[count];
    Queue<Integer> queue = new LinkedList<Integer>();
    truthTable[0] = true; // assume the first person tells the truth
    queue.add(0);

    // Breadth first search on graph
    while (!queue.isEmpty()) {
      int next = queue.remove();
      boolean truth = truthTable[next];
      List<Integer> list = gr.get(next);

      // Go through list and toggle when needed
      for (int i = 0; i < list.size(); i++) {
        int node = list.get(i);
        if (!visited[node]) {
          visited[node] = true;
          truthTable[node] = !truth;
          queue.add(node);
        }
      }
    }

    return truthTable;
  }
 public synchronized void workAllJobs() {
   while (!jobs.isEmpty()) {
     loadJob(jobs.remove());
   }
   while (!shadertoset.empty()) {
     shadertoset.pop().load();
   }
 }
 public Object readObject() throws EOFException {
   synchronized (queue) {
     while (queue.isEmpty())
       try {
         Thread.sleep(250);
       } catch (InterruptedException e) {
       }
     return queue.poll();
   }
 }
Example #9
0
 @SuppressWarnings("incomplete-switch")
 @Override
 public synchronized void run() {
   final List<WorldEditorException> errorList = new ArrayList<WorldEditorException>();
   int counter = 0;
   while (!edits.isEmpty() && counter < 100) {
     try {
       switch (edits.poll().perform()) {
         case SUCCESS:
           successes++;
           break;
         case BLACKLISTED:
           blacklistCollisions++;
           break;
       }
     } catch (final WorldEditorException ex) {
       errorList.add(ex);
     } catch (final Exception ex) {
       getLogger().log(Level.WARNING, "[LogBlock WorldEditor] Exeption: ", ex);
     }
     counter++;
   }
   if (edits.isEmpty()) {
     logblock.getServer().getScheduler().cancelTask(taskID);
     if (errorList.size() > 0)
       try {
         final File file =
             new File(
                 "plugins/LogBlock/error/WorldEditor-"
                     + new SimpleDateFormat("yy-MM-dd-HH-mm-ss").format(System.currentTimeMillis())
                     + ".log");
         file.getParentFile().mkdirs();
         final PrintWriter writer = new PrintWriter(file);
         for (final LookupCacheElement err : errorList) writer.println(err.getMessage());
         writer.close();
       } catch (final Exception ex) {
       }
     errors = errorList.toArray(new WorldEditorException[errorList.size()]);
     notify();
   }
 }
 public Object peekObject() throws EOFException {
   assert false : "Local match shouldn't have best-of-3 early termination";
   synchronized (queue) {
     while (queue.isEmpty()) {
       try {
         Thread.sleep(250);
       } catch (InterruptedException e) {
       }
     }
     return queue.peek();
   }
 }
 public void run() {
   latch = new CountDownLatch(queue.size());
   while (!queue.isEmpty()) {
     final LineCounter counter = queue.remove();
     new Thread(
             new Runnable() {
               public void run() {
                 execute(counter);
                 latch.countDown();
               }
             })
         .start();
   }
   waitOnLatch();
 }
Example #12
0
 public void bfs(int s) {
   Queue<Integer> q = new Queue<Integer>();
   distTo[s] = 0;
   marked[s] = true;
   q.enqueue(s);
   while (!q.isEmpty()) {
     int v = q.dequeue();
     for (Route r : adj[v]) {
       int w = r.other(cities[v]).id() - 1; // index of other city on route
       if (!marked[w]) {
         edgeTo[w] = r;
         distTo[w] = distTo[v] + 1;
         marked[w] = true;
         q.enqueue(w);
       }
     }
   }
 }
  /**
   * Recursively list all files with a certain extension in a directory.
   *
   * @param directory The directory to start searching in.
   * @param extension Only include files with this extension.
   * @return List of files.
   */
  public static List<File> listFilesRecursively(final File directory, final String extension) {
    if (null == directory) {
      throw new IllegalArgumentException("Directory must not be null");
    }

    List<File> files = new ArrayList();
    Queue<File> directories = new LinkedList();
    directories.add(directory);
    while (!directories.isEmpty()) {
      for (File file : directories.poll().listFiles()) {
        if (file.isDirectory()) {
          directories.add(file);
        } else if (file.isFile()) {
          if (extension == null || file.getName().endsWith(extension)) {
            files.add(file);
          }
        }
      }
    }
    return files;
  }
Example #14
0
 @Override
 public Map<String, Object> getValuesDeep() {
   final Tag tag = this.findLastTag(this.path, false);
   if (!(tag instanceof CompoundTag)) {
     return Collections.emptyMap();
   }
   final Queue<Node> node =
       new ArrayDeque<Node>(
           (Collection<? extends Node>) ImmutableList.of((Object) new Node(tag)));
   final Map<String, Object> values = (Map<String, Object>) Maps.newHashMap();
   while (!node.isEmpty()) {
     final Node root = node.poll();
     for (final Map.Entry<String, Tag> entry : root.values.entrySet()) {
       final String key = this.createRelativeKey(root.parent, entry.getKey());
       if (entry.getValue() instanceof CompoundTag) {
         node.add(new Node(key, entry.getValue()));
       } else {
         values.put(key, entry.getValue().getValue());
       }
     }
   }
   return values;
 }
Example #15
0
 public void solve(InputReader in, OutputWriter out) {
   int n = in.nextInt();
   int[][] g = new int[n][n];
   for (int i = 0; i < n; i++) {
     for (int j = 0; j < n; j++) {
       g[i][j] = in.nextInt();
     }
   }
   Queue<int[]> queue =
       new PriorityQueue<int[]>(
           1,
           new Comparator<int[]>() {
             @Override
             public int compare(int[] o1, int[] o2) {
               return o1[1] - o2[1];
             }
           });
   queue.add(new int[] {0, 0});
   boolean[] visited = new boolean[n];
   int res = 0;
   while (!queue.isEmpty()) {
     int[] head = queue.remove();
     int node = head[0];
     int dist = head[1];
     if (!visited[node]) {
       res += dist;
       visited[node] = true;
       for (int i = 0; i < n; i++) {
         if (!visited[i]) {
           queue.add(new int[] {i, g[node][i]});
         }
       }
     }
   }
   out.println(res);
 }
Example #16
0
 public boolean isEmpty() {
   return tokens.isEmpty();
 }
      public void start() {
        if (requests.isEmpty()) return;

        coordinator.send(requests.peek());
      }
 public synchronized void reloadRessources() {
   while (!oldjobs.isEmpty()) {
     oldjobs.remove().load();
   }
 }
Example #19
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");
    }
  }
  @Override
  public void emitTuples() {
    if (currentWindowId <= idempotentStorageManager.getLargestRecoveryWindow()) {
      return;
    }

    if (inputStream == null) {
      try {
        if (currentFile != null && offset > 0) {
          // open file resets offset to 0 so this a way around it.
          int tmpOffset = offset;
          if (fs.exists(new Path(currentFile))) {
            this.inputStream = openFile(new Path(currentFile));
            offset = tmpOffset;
            skipCount = tmpOffset;
          } else {
            currentFile = null;
            offset = 0;
            skipCount = 0;
          }
        } else if (!unfinishedFiles.isEmpty()) {
          retryFailedFile(unfinishedFiles.poll());
        } else if (!pendingFiles.isEmpty()) {
          String newPathString = pendingFiles.iterator().next();
          pendingFiles.remove(newPathString);
          if (fs.exists(new Path(newPathString)))
            this.inputStream = openFile(new Path(newPathString));
        } else if (!failedFiles.isEmpty()) {
          retryFailedFile(failedFiles.poll());
        } else {
          scanDirectory();
        }
      } catch (IOException ex) {
        failureHandling(ex);
      }
    }
    if (inputStream != null) {
      int startOffset = offset;
      String file = currentFile; // current file is reset to null when closed.

      try {
        int counterForTuple = 0;
        while (counterForTuple++ < emitBatchSize) {
          T line = readEntity();
          if (line == null) {
            LOG.info("done reading file ({} entries).", offset);
            closeFile(inputStream);
            break;
          }

          // If skipCount is non zero, then failed file recovery is going on, skipCount is
          // used to prevent already emitted records from being emitted again during recovery.
          // When failed file is open, skipCount is set to the last read offset for that file.
          //
          if (skipCount == 0) {
            offset++;
            emit(line);
          } else {
            skipCount--;
          }
        }
      } catch (IOException e) {
        failureHandling(e);
      }
      // Only when something was emitted from the file then we record it for entry.
      if (offset > startOffset) {
        currentWindowRecoveryState.add(new RecoveryEntry(file, startOffset, offset));
      }
    }
  }
Example #21
0
 public Token lookAhead() {
   if (tokens.isEmpty()) {
     return new Token("EOF", Type.unkown);
   }
   return tokens.peek();
 }
Example #22
0
 public Token getToken() { // rerurn the first Token from the queue
   if (tokens.isEmpty()) {
     return new Token("EOF", Type.unkown);
   }
   return tokens.poll();
 }
Example #23
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);
  }
 public synchronized void workJob() {
   if (!jobs.isEmpty()) {
     loadJob(jobs.remove());
   }
 }
Example #25
0
 public void STS() // method to execute an instruction when the current process finishes
     {
   while (!queue.isEmpty() && (STATE_COMPLETED)) {
     CPU.execute(queue.remove());
   }
 }
  /**
   * A helper to add an entire subtree to a given dependency tree.
   *
   * @param toModify The tree to add the subtree to.
   * @param root The root of the tree where we should be adding the subtree.
   * @param rel The relation to add the subtree with.
   * @param originalTree The orignal tree (i.e., {@link ClauseSplitterSearchProblem#tree}).
   * @param subject The root of the clause to add.
   * @param ignoredEdges The edges to ignore adding when adding this subtree.
   */
  private static void addSubtree(
      SemanticGraph toModify,
      IndexedWord root,
      String rel,
      SemanticGraph originalTree,
      IndexedWord subject,
      Collection<SemanticGraphEdge> ignoredEdges) {
    if (toModify.containsVertex(subject)) {
      return; // This subtree already exists.
    }
    Queue<IndexedWord> fringe = new LinkedList<>();
    Collection<IndexedWord> wordsToAdd = new ArrayList<>();
    Collection<SemanticGraphEdge> edgesToAdd = new ArrayList<>();
    // Search for subtree to add
    for (SemanticGraphEdge edge : originalTree.outgoingEdgeIterable(subject)) {
      if (!ignoredEdges.contains(edge)) {
        if (toModify.containsVertex(edge.getDependent())) {
          // Case: we're adding a subtree that's not disjoint from toModify. This is bad news.
          return;
        }
        edgesToAdd.add(edge);
        fringe.add(edge.getDependent());
      }
    }
    while (!fringe.isEmpty()) {
      IndexedWord node = fringe.poll();
      wordsToAdd.add(node);
      for (SemanticGraphEdge edge : originalTree.outgoingEdgeIterable(node)) {
        if (!ignoredEdges.contains(edge)) {
          if (toModify.containsVertex(edge.getDependent())) {
            // Case: we're adding a subtree that's not disjoint from toModify. This is bad news.
            return;
          }
          edgesToAdd.add(edge);
          fringe.add(edge.getDependent());
        }
      }
    }
    // Add subtree
    // (add subject)
    toModify.addVertex(subject);
    toModify.addEdge(
        root,
        subject,
        GrammaticalRelation.valueOf(Language.English, rel),
        Double.NEGATIVE_INFINITY,
        false);

    // (add nodes)
    wordsToAdd.forEach(toModify::addVertex);
    // (add edges)
    for (SemanticGraphEdge edge : edgesToAdd) {
      assert !toModify.incomingEdgeIterator(edge.getDependent()).hasNext();
      toModify.addEdge(
          edge.getGovernor(),
          edge.getDependent(),
          edge.getRelation(),
          edge.getWeight(),
          edge.isExtra());
    }
  }