예제 #1
0
    /**
     * Adds {@code value} to this heap if it is larger than any of the current elements. Returns
     * {@code true} if {@code value} was added.
     */
    private boolean maybeAddInput(T value) {
      if (maximumSize == 0) {
        // Don't add anything.
        return false;
      }

      // If asQueue == null, then this is the first add after the latest call to the
      // constructor or asList().
      if (asQueue == null) {
        asQueue = new PriorityQueue<>(maximumSize, compareFn);
        for (T item : asList) {
          asQueue.add(item);
        }
        asList = null;
      }

      if (asQueue.size() < maximumSize) {
        asQueue.add(value);
        return true;
      } else if (compareFn.compare(value, asQueue.peek()) > 0) {
        asQueue.poll();
        asQueue.add(value);
        return true;
      } else {
        return false;
      }
    }
예제 #2
0
  public static void main(String args[]) throws IOException {

    String text = "C:\\Users\\Roshan Rajan\\Desktop\\squaredance.txt";
    String gender = "";
    PriorityQueue<String> men = new PriorityQueue<String>();
    PriorityQueue<String> women = new PriorityQueue<String>();
    BufferedReader input = new BufferedReader(new FileReader(text));
    String line = null;
    while ((line = input.readLine()) != null) {
      gender = line.substring(0, 1);
      if (gender.equals("M")) men.add(line.substring(2));
      else women.add(line.substring(2));
    }
    input.close();

    while (!men.isEmpty() && !women.isEmpty()) {
      System.out.println("The couples are ");
      System.out.println(men.poll() + " is Dancing with " + women.poll());
    }
    if (men.isEmpty()) {
      System.out.println(women.size() + " girls are Waiting to Dance");
      System.out.println(women.peek() + " is the first one waiting");
    }
    if (women.isEmpty()) {
      System.out.println(men.size() + " guys are Waiting to Dance");
      System.out.println(men.peek() + " is the first one waiting");
    }
  }
  /**
   * Get top N elements
   *
   * @param vec the vec to extract the top elements from
   * @param N the number of elements to extract
   * @return the indices and the sorted top N elements
   */
  private static List<Double> getTopN(INDArray vec, int N) {
    ArrayComparator comparator = new ArrayComparator();
    PriorityQueue<Double[]> queue = new PriorityQueue<>(vec.rows(), comparator);

    for (int j = 0; j < vec.length(); j++) {
      final Double[] pair = new Double[] {vec.getDouble(j), (double) j};
      if (queue.size() < N) {
        queue.add(pair);
      } else {
        Double[] head = queue.peek();
        if (comparator.compare(pair, head) > 0) {
          queue.poll();
          queue.add(pair);
        }
      }
    }

    List<Double> lowToHighSimLst = new ArrayList<>();

    while (!queue.isEmpty()) {
      double ind = queue.poll()[1];
      lowToHighSimLst.add(ind);
    }
    return Lists.reverse(lowToHighSimLst);
  }
예제 #4
0
  public void reduce(
      Text key, Iterator<Text> values, OutputCollector<Text, Text> output, Reporter reporter)
      throws IOException {

    while (values.hasNext()) {
      String line = values.next().toString();
      String[] tokens = line.split(",");

      try {
        double latitude = (Double.parseDouble(tokens[2]));
        double longitude = (Double.parseDouble(tokens[3]));

        Tuple t = new Tuple(longitude, latitude, line);
        t.setDistance(fp);
        if (queue.size() < k) {
          queue.add(t);
        } else {
          if (t.distance < queue.peek().distance) {
            queue.add(t);
            queue.remove();
          }
        }

      } catch (Exception c) {

      }
    }

    while (!queue.isEmpty()) {
      output.collect(new Text("1"), new Text(queue.remove().tupleData));
    }
  }
예제 #5
0
파일: HW19.java 프로젝트: KoolKow/apcs-hw
 public void add(int x) {
   if (min.size() <= max.size()) {
     min.add(x);
   } else {
     max.add(x);
   }
 }
예제 #6
0
 public ListNode mergeKLists(ArrayList<ListNode> lists) {
   if (lists == null || lists.isEmpty()) return null;
   PriorityQueue<ListNode> heap =
       new PriorityQueue<ListNode>(
           lists.size(),
           new Comparator<ListNode>() {
             public int compare(ListNode o1, ListNode o2) {
               return o1.data > o2.data ? 1 : (o1.data < o2.data ? -1 : 0);
             }
           });
   for (ListNode node : lists) {
     if (node != null) {
       heap.add(node);
     }
   }
   ListNode head = null, cur = null;
   while (!heap.isEmpty()) {
     if (head == null) {
       head = heap.poll();
       cur = head;
     } else {
       cur.next = heap.poll();
       cur = cur.next;
     }
     if (cur.next != null) {
       heap.add(cur.next);
     }
   }
   return head;
 }
예제 #7
0
  private void Loop() {
    while (!H.isEmpty()) {
      Cell v = H.poll();
      if (Log.ON) Log.write("popped: " + potentialField[v.col][v.row]);
      frozenDjogurt[v.col][v.row] = true;
      for (Cell vn : map.doSomeMagic(v)) {
        if (Log.ON) {
          Log.write("\n" + toString(v));
          Log.write("\n" + printStack());
        }
        if (!(map.cells[vn.col][vn.row].type == CellType.OBSTACLE)) {
          if (!frozenDjogurt[vn.col][vn.row]) {
            double d = computeArrivalTime(vn);
            if (d > maxElement) maxElement = d;
            if (!H.contains(vn)) {

              potentialField[vn.col][vn.row] = d;
              H.add(vn);
            } else {
              //							if(potentialField[vn.col][vn.row] > d)
              //							{
              H.remove(vn);
              potentialField[vn.col][vn.row] = d;
              H.add(vn);
              //							}
            }
          }
        }
      }
    }
  }
예제 #8
0
  public static ListNode mergeKlists(List<ListNode> lists) {
    if (lists.size() == 0) return null;

    PriorityQueue<ListNode> p =
        new PriorityQueue<ListNode>(
            lists.size(),
            new Comparator<ListNode>() {
              @Override
              public int compare(ListNode a, ListNode b) {
                return a.val - b.val;
              }
            });

    for (ListNode list : lists) {
      if (list != null) p.add(list);
    }

    ListNode head = new ListNode(0);
    ListNode result = head;

    while (p.size() > 0) {
      ListNode temp = p.poll();
      result.next = temp;

      if (temp.next != null) {
        p.add(temp.next);
      }

      result = result.next;
    }
    return head.next;
  }
  public void PQOrdering() {
    PriorityQueue<String> pq = new PriorityQueue<String>();
    pq.add("5");
    pq.add("3");
    pq.add("1");
    pq.add("2");
    pq.add("4");
    pq.add("6");

    System.out.println("Unordered: " + pq); // Unordered: [1, 2, 3, 5, 4, 6]

    Iterator<String> itr = pq.iterator();
    System.out.print("Unordered Itr: ");
    while (itr.hasNext()) {
      System.out.print(itr.next() + ", "); // Unordered Itr: 1, 2, 3, 5, 4, 6,
    }

    System.out.println("");
    System.out.print("Unordered Arrays: ");
    Object[] obj = pq.toArray();
    for (Object o : obj) {
      System.out.print(o + ", "); // Unordered Arrays: 1, 2, 3, 5, 4, 6,
    }

    // To order a PQ
    System.out.print("\nOrdered:");
    while (!pq.isEmpty()) {
      System.out.print(pq.poll() + ", "); // Ordered: 1, 2, 3, 4, 5, 6,
    }
    System.out.println("********************************************");
  }
예제 #10
0
 public static void main(String args[]) {
   FileReader.filehandler();
   Node root = new Node((Max_Row - startx), starty, 0, 0, null, Message_Obtained, direction);
   open.add(root);
   closed.add(root);
   recursive_dfs(root);
 }
예제 #11
0
파일: 2421.java 프로젝트: jmankhan/ACM
 public static void main(String[] args) {
   Scanner in = new Scanner(System.in);
   PriorityQueue<Node> pq = new PriorityQueue<Node>();
   HashSet<Integer> visited = new HashSet<Integer>();
   int n = in.nextInt();
   int[][] am = new int[n][n];
   for (int i = 0; i < n; i++)
     for (int j = 0; j < n; j++) {
       am[i][j] = in.nextInt();
       if (i == j) am[i][j] = Integer.MAX_VALUE;
     }
   n = in.nextInt();
   int a, b;
   while (n-- > 0) {
     a = in.nextInt() - 1;
     b = in.nextInt() - 1;
     am[a][b] = 0;
     am[b][a] = 0;
   }
   int ret = 0;
   pq.add(new Node(0, 0));
   Node curr;
   while (!pq.isEmpty()) {
     curr = pq.poll();
     if (visited.contains(curr.a)) continue;
     ret += curr.w;
     visited.add(curr.a);
     for (int i = 0; i < am.length; i++) {
       pq.add(new Node(i, am[curr.a][i]));
     }
   }
   System.out.println(ret);
 }
예제 #12
0
  public static void computePaths(Vertex source, ArrayList<String> ziel) {
    source.minDistance = 0.;
    PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
    vertexQueue.add(source);
    while (!vertexQueue.isEmpty()) {
      Vertex u = vertexQueue.poll();

      // Visit each edge exiting u
      for (Edge e : u.adjacencies) {
        Vertex v = e.target;
        double weight = e.weight;
        double distanceThroughU = u.minDistance + weight;
        if (distanceThroughU < v.minDistance) {
          vertexQueue.remove(v);
          v.minDistance = distanceThroughU;
          v.previous = u;
          vertexQueue.add(v);
        }
      }
      if (ziel.contains(u.name)) {
        vertexQueue.clear();
        break;
      }
    }
  }
예제 #13
0
  public List<Pair> assignJobsNew(Queue<Integer> jobs, int numWorkers) {
    List<Pair> pairs = new LinkedList<>();

    PriorityQueue<JobThread> priorityQueue =
        new PriorityQueue<>((x, y) -> Long.compare(x.startTime, y.startTime));
    for (int i = 0; i < numWorkers; i++) {
      priorityQueue.add(new JobThread());
    }

    while (!jobs.isEmpty()) {
      int duration = jobs.poll();

      boolean check = true;
      while (check) {
        JobThread peek = priorityQueue.poll();
        if (peek.hasFreeTime()) {
          peek.duration = duration;
          pairs.add(new Pair(peek.workerId, peek.newStartTime()));
        } else {
          peek.tick();
        }

        if (priorityQueue.isEmpty()) {
          check = false;
        }
        priorityQueue.add(peek);
      }
    }
    return pairs;
  }
예제 #14
0
 public ListNode mergeKLists(ListNode[] lists) {
   ListNode sentinel = new ListNode(0);
   ListNode current = sentinel;
   PriorityQueue<ListNode> heap =
       new PriorityQueue<>(
           (e1, e2) -> {
             if (e1.val > e2.val) {
               return 1;
             } else if (e1.val < e2.val) {
               return -1;
             } else {
               return 0;
             }
           });
   for (ListNode node : lists) {
     if (node != null) {
       heap.add(node);
     }
   }
   while (heap.isEmpty() == false) {
     ListNode nodeWithMinValue = heap.poll();
     current.next = nodeWithMinValue;
     nodeWithMinValue = nodeWithMinValue.next;
     if (nodeWithMinValue != null) {
       heap.add(nodeWithMinValue);
     }
   }
   return sentinel.next;
 }
예제 #15
0
 public static List<Vertex> compute(Graph graph) {
   List<Vertex> resultList = new LinkedList<Vertex>();
   Vertex[] vertexes = graph.getVertexes();
   List<EdgeFrom>[] edgesTo = graph.getEdgesTo();
   double[] d = new double[vertexes.length];
   Arrays.fill(d, Double.MAX_VALUE);
   d[d.length - 1] = 0;
   int[] path = new int[vertexes.length];
   Arrays.fill(path, -1);
   PriorityQueue<State> que = new PriorityQueue<State>();
   que.add(new State(0, vertexes.length - 1));
   while (!que.isEmpty()) {
     State p = que.poll();
     if (d[p.vertex] < p.cost) continue;
     for (EdgeFrom edgeFrom : edgesTo[p.vertex]) {
       if (d[edgeFrom.from] > d[p.vertex] + edgeFrom.weight) {
         d[edgeFrom.from] = d[p.vertex] + edgeFrom.weight;
         que.add(new State(d[edgeFrom.from], edgeFrom.from));
         path[edgeFrom.from] = p.vertex;
       }
     }
   }
   for (int t = 0; t != -1; t = path[t]) {
     resultList.add(vertexes[t]);
   }
   return resultList;
 }
 // Busqueda usando A*
 public static int search() {
     HashSet<State> v = new HashSet<>();
     Giros mano = new Giros();
     ArrayList<int[][]>aux;
     
     finall = inicial.createGoalState();
     Q.add(inicial);
     Node actual;
     int cont = 0;
     
     while ( !(actual = Q.remove()).estado.equals(finall.estado) ) {
         
         if(v.contains(actual.estado)) 
             continue;
         System.out.println(actual.estado+" "+actual.costo_hasta_aqui+" "+actual.costo_total);
         System.out.println("->\n"+((NodeCubo)actual).getValue() );
         
         v.add(actual.estado);
         int ca = actual.costo_hasta_aqui + 1;
         
         //Realiza Movimientos
         for( int i=0; i<12; i++ ){
             aux = mano.girar( ((Cubo)actual.getValue()).getCubo(), i);
             Node nuevo = new NodeCubo(ca, ca+Heuristica.h1((Cubo)actual.getValue()), new Cubo( aux, ((Cubo)inicial.getValue()).getColors() ) );
             Q.add( (Node)nuevo );
         }
         cont++;
     }
     return cont;
 }
예제 #17
0
  private void visitAllStartSegments(
      final RoutingContext ctx,
      RouteSegment start,
      PriorityQueue<RouteSegment> graphDirectSegments,
      TLongObjectHashMap<RouteSegment> visitedSegments,
      int startX,
      int startY)
      throws IOException {
    // mark as visited code seems to be duplicated
    long nt = (start.road.getId() << 8l) + start.segmentStart;
    visitedSegments.put(nt, start);
    graphDirectSegments.add(start);

    loadRoutes(
        ctx,
        (startX >> (31 - ctx.getZoomToLoadTileWithRoads())),
        (startY >> (31 - ctx.getZoomToLoadTileWithRoads())));
    long ls = (((long) startX) << 31) + (long) startY;
    RouteSegment startNbs = ctx.routes.get(ls);
    while (startNbs != null) { // startNbs.road.id >> 1, start.road.id >> 1
      if (startNbs.road.getId() != start.road.getId()) {
        startNbs.parentRoute = start;
        startNbs.parentSegmentEnd = start.segmentStart;
        startNbs.distanceToEnd = start.distanceToEnd;

        // duplicated to be sure start is added
        nt = (startNbs.road.getId() << 8l) + startNbs.segmentStart;
        visitedSegments.put(nt, startNbs);
        graphDirectSegments.add(startNbs);
      }
      startNbs = startNbs.next;
    }
  }
예제 #18
0
 private void expandLandmarkTo() {
   LandmarksToTravelTimeComparator comparator =
       new LandmarksToTravelTimeComparator(this.nodeData, this.landmarkIdx);
   PriorityQueue<Node> pendingNodes = new PriorityQueue<>(100, comparator);
   LandmarksData role = (LandmarksData) this.nodeData.get(this.landmark);
   role.setToLandmarkTravelTime(this.landmarkIdx, 0.0);
   role.setFromLandmarkTravelTime(this.landmarkIdx, 0.0);
   pendingNodes.add(this.landmark);
   while (!pendingNodes.isEmpty()) {
     Node node = pendingNodes.poll();
     double toTravTime =
         ((LandmarksData) this.nodeData.get(node)).getToLandmarkTravelTime(this.landmarkIdx);
     LandmarksData role2;
     for (Link l : node.getInLinks().values()) {
       Node n = l.getFromNode();
       double linkTravTime = this.costFunction.getLinkMinimumTravelDisutility(l);
       role2 = (LandmarksData) this.nodeData.get(n);
       double totalTravelTime = toTravTime + linkTravTime;
       if (role2.getToLandmarkTravelTime(this.landmarkIdx) > totalTravelTime) {
         role2.setToLandmarkTravelTime(this.landmarkIdx, totalTravelTime);
         pendingNodes.add(n);
       }
     }
   }
 }
예제 #19
0
 public static void main(String args[]) throws Exception {
   //		try {System.setIn(new FileInputStream("in.txt"));} catch(Exception e) {}
   st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
   BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
   PriorityQueue<Pair> pq = new PriorityQueue<Pair>(562500);
   int ans[] = new int[750], list[] = new int[750], n;
   while (st.nextToken() != StreamTokenizer.TT_EOF) {
     n = (int) st.nval;
     for (int x = 0; x < n; x++) {
       for (int i = 0; i < n; i++) list[i] = getInt();
       Arrays.sort(list, 0, n);
       if (x == 0) for (int i = 0; i < n; i++) ans[i] = list[i];
       else {
         pq.clear();
         for (int i = 0; i < n; i++) pq.add(new Pair(ans[i] + list[0], 0));
         for (int i = 0; i < n; i++) {
           Pair p = pq.poll();
           ans[i] = p.x;
           if (p.y + 1 < n) pq.add(new Pair(p.x - list[p.y] + list[p.y + 1], p.y + 1));
         }
       }
     }
     for (int i = 0; i < n; i++) out.write(ans[i] + (i == n - 1 ? "\n" : " "));
   }
   out.flush();
 }
예제 #20
0
  @Override
  public CategoricalResults classify(DataPoint data) {
    CategoricalResults cr = new CategoricalResults(predicting.getNumOfCategories());

    // Use a priority que so that we always pick the two lowest value class labels, makes indexing
    // into the oneVsOne array simple
    PriorityQueue<Integer> options = new PriorityQueue<Integer>(predicting.getNumOfCategories());
    for (int i = 0; i < cr.size(); i++) options.add(i);

    CategoricalResults subRes;
    int c1, c2;
    // We will now loop through and repeatedly pick two combinations, and eliminate the loser, until
    // there is one winer
    while (options.size() > 1) {
      c1 = options.poll();
      c2 = options.poll();

      subRes = oneVone[c1][c2 - c1 - 1].classify(data);

      if (subRes.mostLikely() == 0) // c1 wins, c2 no longer a candidate
      options.add(c1);
      else // c2 wins, c1 no onger a candidate
      options.add(c2);
    }

    cr.setProb(options.peek(), 1.0);

    return cr;
  }
예제 #21
0
    public void solve(int testNumber, InputReader in, OutputWriter out) {
      String X;
      PriorityQueue<Integer> pq = new PriorityQueue<>();
      Stack<Integer> stack = new Stack<>();

      while ((X = in.next()) != null) {
        int x = Integer.valueOf(X);
        pq.add(x);
        int sz = pq.size();
        int median = 0;

        if (sz == 1) {
          median = pq.peek();
        } else {
          for (int i = 0; i <= sz / 2; i++) {
            stack.add(pq.poll());
            if ((i == (sz / 2) - 1 && sz % 2 == 0) || i == (sz / 2)) {
              median += stack.peek();
            }
          }
          if (sz % 2 == 0) median /= 2;
        }

        while (!stack.isEmpty()) pq.add(stack.pop());
        out.printLine(median);
      }
    }
예제 #22
0
  private int Asearch(Game game) {
    Comparator<PacManNode> comparator = new PacComparator();
    PriorityQueue<PacManNode> open = new PriorityQueue<PacManNode>(1, comparator);
    // because we are conducting tree-search, so 'closed' may not be used, but I'll still leave it
    // here
    HashSet<PacManNode> closed = new HashSet<PacManNode>();

    open.add(new PacManNode(game.copy(), 0));
    int score = game.getScore();
    while (!open.isEmpty()) {
      PacManNode node = open.poll();
      closed.add(node);
      if (node.depth == DEPTH) {
        // System.out.
        score = node.currentState.getScore();
        return score;
      }
      MOVE[] moves = MOVE.values();
      for (MOVE move : moves) {
        Game gameCopy = node.currentState.copy();
        gameCopy.advanceGame(move, ghosts.getMove(gameCopy, 0));
        open.add(new PacManNode(gameCopy, node.depth + 1));
      }
    }
    return score;
  }
 public int[] maxSlidingWindow(int[] nums, int k) {
   if (nums.length == 0 || k == 0) {
     return new int[] {};
   }
   int[] result = new int[nums.length - k + 1];
   PriorityQueue<Integer> priorityQueue =
       new PriorityQueue<Integer>(
           k,
           new Comparator<Integer>() {
             @Override
             public int compare(Integer o1, Integer o2) {
               if (o1 < o2) {
                 return 1;
               } else if (o1 > o2) {
                 return -1;
               } else {
                 return 0;
               }
             }
           });
   Deque<Integer> deque = new LinkedList<Integer>();
   for (int i = 0; i < k; i++) {
     deque.addLast(nums[i]);
     priorityQueue.add(nums[i]);
   }
   for (int i = k; i < nums.length; i++) {
     result[i - k] = priorityQueue.peek();
     int first = deque.removeFirst();
     priorityQueue.remove(first);
     deque.addLast(nums[i]);
     priorityQueue.add(nums[i]);
   }
   result[result.length - 1] = priorityQueue.peek();
   return result;
 }
예제 #24
0
  public static void main(String[] args) {
    // Convert het woord naar chars
    String woord = "bananen";
    ArrayList<Character> chars = new ArrayList<>();
    ArrayList<HuffKnoop> knopen = new ArrayList<>();
    for (int i = 0; i < woord.length(); i++) {
      chars.add(woord.charAt(i));
    }

    // 1. Frequentie van tekens
    Set<Character> uniqueChars = new HashSet<>(chars);
    for (char c : uniqueChars) {
      knopen.add(new HuffKnoop(c, Collections.frequency(chars, c), null, null));
    }

    // 2. Sorteer de tekens op frequentie
    PriorityQueue queue =
        new PriorityQueue(
            uniqueChars.size(),
            new Comparator<HuffKnoop>() {
              @Override
              public int compare(HuffKnoop o1, HuffKnoop o2) {
                return o1.frequentie - o2.frequentie;
              }
            });

    for (HuffKnoop knoop : knopen) {
      queue.add(knoop);
    }

    // 3. Maken van de huffman boom.
    while (queue.size() > 1) {
      HuffKnoop knoopLinks = (HuffKnoop) queue.poll();
      HuffKnoop knoopRechts = (HuffKnoop) queue.poll();
      queue.add(
          new HuffKnoop(
              '\0', knoopLinks.frequentie + knoopRechts.frequentie, knoopLinks, knoopRechts));
    }

    // 4. Aflezen van de codes
    boom = (HuffKnoop) queue.poll();
    generateCodes(boom, "");

    Iterator it = codes.entrySet().iterator();
    while (it.hasNext()) {
      Map.Entry pair = (Map.Entry) it.next();
      System.out.println(pair.getKey() + " " + pair.getValue());
    }

    // 5. Coderen
    String encodedMessage = encodeMessage(woord);
    System.out.println(encodedMessage);

    // 6. Decoderen
    String decodedMessage = decodeMessage(encodedMessage);
    System.out.println(decodedMessage);
  }
예제 #25
0
파일: test.java 프로젝트: liamleahy/cs61b
 public static void main(String[] args) {
   PriorityQueue<TST.Wrapper> tm = new PriorityQueue<TST.Wrapper>(3, new TST.Wrapper.compr());
   tm.add(new TST.Wrapper(1.0, "test1"));
   tm.add(new TST.Wrapper(2.0, "test2"));
   tm.add(new TST.Wrapper(3.0, "test3"));
   tm.add(new TST.Wrapper(0.1, "test4"));
   for (TST.Wrapper w : tm) {
     System.out.println(w.val);
   }
 }
예제 #26
0
 @Test
 public void test1p() {
   PriorityQueue<Integer> queue = new PriorityQueue<>(4);
   queue.add(1);
   queue.add(2);
   queue.add(3);
   queue.add(4);
   Assert.assertEquals(Integer.valueOf(1), queue.poll());
   Assert.assertFalse(queue.poll().equals(4));
 }
 public static void main(String[] args) {
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   try {
     N = Integer.parseInt(br.readLine());
     P = new int[N][N];
     RP = new boolean[N][N];
     D = new double[N];
     nodes = new HNode[N];
     Fix = new boolean[N];
     String[] chunks;
     for (int i = 0; i < N; i++) {
       chunks = br.readLine().split(" ");
       for (int j = 0; j < N; j++) {
         P[i][j] = Integer.parseInt(chunks[j]);
         if (P[i][j] > 0 && i != j) RP[j][i] = true;
       }
     }
     if (N == 1) {
       System.out.println(0);
       return;
     }
     for (int i = 0; i < N - 1; i++) {
       if (RP[N - 1][i]) {
         D[i] = (double) 100 / (double) P[i][N - 1];
         nodes[i] = new HNode(D[i], i, 1, (1.0 - (double) P[i][N - 1] / (double) 100));
         heap.add(nodes[i]);
       } else {
         D[i] = Double.MAX_VALUE;
         nodes[i] = new HNode(D[i], i, 1, 1);
       }
     }
     HNode minHeap;
     while (!heap.isEmpty()) {
       minHeap = heap.remove();
       if (minHeap.id == 0) {
         System.out.println(minHeap.dis);
         break;
       }
       Fix[minHeap.id] = true;
       for (int j = 0; j < N - 1; j++) {
         if (RP[minHeap.id][j] && !Fix[j]) { // j is the parent of min heap
           double p = (double) P[j][minHeap.id] / (double) 100;
           nodes[j].a = nodes[j].a + nodes[j].b * p * minHeap.dis;
           nodes[j].b = nodes[j].b * (1 - p);
           double newDis = nodes[j].a / (1 - nodes[j].b);
           heap.remove(nodes[j]);
           nodes[j].dis = newDis;
           heap.add(nodes[j]);
         }
       }
     }
   } catch (IOException ioe) {
     ioe.printStackTrace();
   }
 }
  @SuppressWarnings("unchecked")
  public int getMinimumMoves(String[] board) {
    PriorityQueue<Long> pq = new PriorityQueue<Long>();
    HashMap<Long, Integer> map = new HashMap<Long, Integer>();

    ArrayList<Integer> pieces = new ArrayList<Integer>();
    for (int i = 0; i < 5; i++) {
      for (int j = 0; j < 5; j++) {
        if (board[i].charAt(j) == '*') {
          pieces.add((i << 3) | j);
        }
      }
    }
    N = pieces.size();

    pq.add(pack(pieces));
    while (pq.size() > 0) {
      long a = pq.poll();
      long k = a & 0xFFFFFFFFL;
      int c = (int) (a >>> 32);

      if (map.containsKey(k)) continue;
      map.put(k, c);

      ArrayList<Integer> unpack = unpack(k);

      if (connected(unpack)) return c;

      for (int i = 0; i < N; i++) {
        int piece = unpack.get(i);
        int x = piece >>> 3;
        int y = piece & 0x7;

        for (int j = 0; j < dir.length; j++) {
          ArrayList<Integer> copy = (ArrayList<Integer>) unpack.clone();
          copy.remove(i);

          if (x + dir[j][0] < 0 || x + dir[j][0] >= 5 || y + dir[j][1] < 0 || y + dir[j][1] >= 5)
            continue;
          int newp = ((x + dir[j][0]) << 3) | (y + dir[j][1]);

          if (copy.contains(newp)) continue;
          copy.add(newp);

          long test = pack(copy);

          if (map.get(test) == null || map.get(test) > c + 1) {
            pq.add((((long) c + 1) << 32) | test);
          }
        }
      }
    }
    return -1;
  }
예제 #29
0
  /**
   * A* pathfinding algorithm
   *
   * @param grid the grid to be used for pathfinding
   * @param x target x coordinate in grid form
   * @param y target y coordinate in grid form
   * @return The next move to make for the ghost
   */
  public Node pathFind(Grid grid, int x, int y) {
    // Set target x, y
    Node.tx = x;
    Node.ty = y;

    Node current = null, temp;
    int block;

    PriorityQueue<Node> opened = new PriorityQueue<Node>();
    HashSet<Node> closed = new HashSet<Node>();

    temp =
        new Node(
            this.x / Board.BLOCKSIZE, this.y / Board.BLOCKSIZE, 0); // current location of ghost
    temp.init();
    temp.setDir(dx, dy);
    opened.offer(temp);

    while (!opened.isEmpty()) {
      current = opened.poll(); // get best node
      closed.add(current); // add node to closed set (visited)

      if (current.hCost == 0) // if future cost is 0, then it is target node
      break;

      block = grid.screenData[current.y][current.x];

      // If can move, not abrupt, and unvisited, add to opened
      if ((block & 1) == 0 && current.dir != 3) // Can move and not abrupt
      {
        temp = current.getChild(-1, 0); // get child node
        if (!closed.contains(temp)) // Unvisited
        opened.add(temp);
      }
      if ((block & 2) == 0 && current.dir != 4) {
        temp = current.getChild(0, -1);
        if (!closed.contains(temp)) opened.add(temp);
      }
      if ((block & 4) == 0 && current.dir != 1) {
        temp = current.getChild(1, 0);
        if (!closed.contains(temp)) opened.add(temp);
      }
      if ((block & 8) == 0 && current.dir != 2) {
        temp = current.getChild(0, 1);
        if (!closed.contains(temp)) opened.add(temp);
      }
    }

    // if current.parent == null, then ghost is on pacman.  Handle it by moving randomly
    // current.parent.parent == null, then current is best next move
    while (current.parent != null && current.parent.parent != null) current = current.parent;

    return current;
  }
  private boolean undirectedAdd(UndirectedWeightedEdge e, UndirectedNode s) {
    HashMap<Node, Node> parent = parents.get(s);
    HashMap<Node, Integer> height = heights.get(s);

    IntWeight eWeight = (IntWeight) e.getWeight();

    UndirectedNode n1 = e.getNode1();
    UndirectedNode n2 = e.getNode2();

    if (height.get(n1) > height.get(n2)) {
      n1 = e.getNode2();
      n2 = e.getNode1();
    }

    if (height.get(n1) + (int) eWeight.getWeight() >= height.get(n2)
        || height.get(n1) + (int) eWeight.getWeight() < 0) {
      return true;
    }
    if (height.get(n2) != Integer.MAX_VALUE) apsp.decr(height.get(n2));
    apsp.incr(height.get(n1) + (int) eWeight.getWeight());
    height.put(n2, height.get(n1) + (int) eWeight.getWeight());
    parent.put(n2, n1);
    PriorityQueue<Node> q = new PriorityQueue<>();
    q.add(n2);
    while (!q.isEmpty()) {
      Node current = q.poll();

      if (height.get(current) == Integer.MAX_VALUE) {
        break;
      }

      for (IElement edge : current.getEdges()) {
        UndirectedWeightedEdge d = (UndirectedWeightedEdge) edge;

        Node neighbor = d.getDifferingNode(current);
        IntWeight dWeight = (IntWeight) d.getWeight();

        int alt = height.get(current) + (int) dWeight.getWeight();

        if (alt < height.get(neighbor)) {
          if (height.get(neighbor) != Integer.MAX_VALUE) apsp.decr(height.get(neighbor));
          apsp.incr(alt);
          height.put(neighbor, alt);
          parent.put(neighbor, current);
          if (q.contains(neighbor)) {
            q.remove(neighbor);
          }
          q.add(neighbor);
        }
      }
    }
    return true;
  }