Search in sources :

Example 26 with PriorityQueue

use of java.util.PriorityQueue in project leetcode by demonSong.

the class SolutionDay13_L0407 method trapRainWater.

public int trapRainWater(int[][] heightMap) {
    int row = heightMap.length;
    if (row <= 2)
        return 0;
    int col = heightMap[0].length;
    if (col <= 2)
        return 0;
    int[][] dir = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
    // 从最低的cell遍历
    PriorityQueue<Cell> queue = new PriorityQueue<>(1, new Comparator<Cell>() {

        @Override
        public int compare(Cell o1, Cell o2) {
            return o1.height - o2.height;
        }
    });
    boolean[][] visited = new boolean[row][col];
    for (int i = 0; i < row; i++) {
        visited[i][0] = true;
        visited[i][col - 1] = true;
        queue.offer(new Cell(i, 0, heightMap[i][0]));
        queue.offer(new Cell(i, col - 1, heightMap[i][col - 1]));
    }
    for (int i = 0; i < col; i++) {
        visited[0][i] = true;
        visited[row - 1][i] = true;
        queue.offer(new Cell(0, i, heightMap[0][i]));
        queue.offer(new Cell(row - 1, i, heightMap[row - 1][i]));
    }
    int area = 0;
    while (!queue.isEmpty()) {
        Cell cell = queue.poll();
        for (int[] d : dir) {
            int nrow = cell.row + d[0];
            int ncol = cell.col + d[1];
            if (nrow >= 0 && nrow < row && ncol >= 0 && ncol < col && !visited[nrow][ncol]) {
                visited[nrow][ncol] = true;
                area += Math.max(0, cell.height - heightMap[nrow][ncol]);
                queue.offer(new Cell(nrow, ncol, Math.max(heightMap[nrow][ncol], cell.height)));
            }
        }
    }
    return area;
}
Also used : PriorityQueue(java.util.PriorityQueue) Cell(javafx.scene.control.Cell)

Example 27 with PriorityQueue

use of java.util.PriorityQueue in project deeplearning4j by deeplearning4j.

the class GraphVectorsImpl method verticesNearest.

@Override
public int[] verticesNearest(int vertexIdx, int top) {
    INDArray vec = lookupTable.getVector(vertexIdx).dup();
    double norm2 = vec.norm2Number().doubleValue();
    PriorityQueue<Pair<Double, Integer>> pq = new PriorityQueue<>(lookupTable.getNumVertices(), new PairComparator());
    Level1 l1 = Nd4j.getBlasWrapper().level1();
    for (int i = 0; i < numVertices(); i++) {
        if (i == vertexIdx)
            continue;
        INDArray other = lookupTable.getVector(i);
        double cosineSim = l1.dot(vec.length(), 1.0, vec, other) / (norm2 * other.norm2Number().doubleValue());
        pq.add(new Pair<>(cosineSim, i));
    }
    int[] out = new int[top];
    for (int i = 0; i < top; i++) {
        out[i] = pq.remove().getSecond();
    }
    return out;
}
Also used : INDArray(org.nd4j.linalg.api.ndarray.INDArray) Level1(org.nd4j.linalg.api.blas.Level1) PriorityQueue(java.util.PriorityQueue) Pair(org.deeplearning4j.berkeley.Pair)

Example 28 with PriorityQueue

use of java.util.PriorityQueue in project druid by druid-io.

the class ImmutableConciseSet method doUnion.

private static ImmutableConciseSet doUnion(Iterator<ImmutableConciseSet> sets) {
    IntList retVal = new IntList();
    // Use PriorityQueue, because sometimes as much as 20k of bitsets are unified, and the asymptotic complexity of
    // keeping bitsets in a sorted array (n^2), as in doIntersection(), becomes more important factor than PriorityQueue
    // inefficiency.
    // Need to specify initial capacity because JDK 7 doesn't have Comparator-only constructor of PriorityQueue
    PriorityQueue<WordIterator> theQ = new PriorityQueue<>(11, UNION_COMPARATOR);
    // populate priority queue
    while (sets.hasNext()) {
        ImmutableConciseSet set = sets.next();
        if (set != null && !set.isEmpty()) {
            WordIterator itr = set.newWordIterator();
            itr.word = itr.next();
            theQ.add(itr);
        }
    }
    int currIndex = 0;
    List<WordIterator> changedIterators = new ArrayList<>();
    while (!theQ.isEmpty()) {
        // grab the top element from the priority queue
        WordIterator itr = theQ.poll();
        int word = itr.getWord();
        // to fill the space
        if (currIndex < itr.startIndex) {
            addAndCompact(retVal, itr.startIndex - currIndex - 1);
            currIndex = itr.startIndex;
        }
        if (ConciseSetUtils.isLiteral(word)) {
            // advance all other literals
            while (!theQ.isEmpty() && theQ.peek().startIndex == itr.startIndex) {
                WordIterator i = theQ.poll();
                int w = i.getWord();
                // if we still have zero fills with flipped bits, OR them here
                if (ConciseSetUtils.isLiteral(w)) {
                    word |= w;
                } else {
                    int flipBitLiteral = ConciseSetUtils.getLiteralFromZeroSeqFlipBit(w);
                    if (flipBitLiteral != ConciseSetUtils.ALL_ZEROS_LITERAL) {
                        word |= flipBitLiteral;
                        i.advanceTo(itr.wordsWalked);
                    }
                }
                if (i.hasNext()) {
                    i.word = i.next();
                    changedIterators.add(i);
                }
            }
            // advance the set with the current literal forward and push result back to priority queue
            addAndCompact(retVal, word);
            currIndex++;
            if (itr.hasNext()) {
                itr.word = itr.next();
                changedIterators.add(itr);
            }
        } else if (ConciseSetUtils.isZeroSequence(word)) {
            int flipBitLiteral;
            while (!theQ.isEmpty() && theQ.peek().startIndex == itr.startIndex) {
                WordIterator i = theQ.poll();
                int w = i.getWord();
                flipBitLiteral = ConciseSetUtils.getLiteralFromZeroSeqFlipBit(w);
                if (flipBitLiteral != ConciseSetUtils.ALL_ZEROS_LITERAL) {
                    i.word = flipBitLiteral;
                    changedIterators.add(i);
                } else if (i.hasNext()) {
                    i.word = i.next();
                    changedIterators.add(i);
                }
            }
            // check if a literal needs to be created from the flipped bits of this sequence
            flipBitLiteral = ConciseSetUtils.getLiteralFromZeroSeqFlipBit(word);
            if (flipBitLiteral != ConciseSetUtils.ALL_ZEROS_LITERAL) {
                itr.word = flipBitLiteral;
                changedIterators.add(itr);
            } else if (itr.hasNext()) {
                itr.word = itr.next();
                changedIterators.add(itr);
            }
        } else {
            assert ConciseSetUtils.isOneSequence(word);
            // extract a literal from the flip bits of the one sequence
            int flipBitLiteral = ConciseSetUtils.getLiteralFromOneSeqFlipBit(word);
            // advance everything past the longest ones sequence
            while (!theQ.isEmpty() && theQ.peek().startIndex < itr.wordsWalked) {
                WordIterator i = theQ.poll();
                int w = i.getWord();
                if (i.startIndex == itr.startIndex) {
                    // position
                    if (ConciseSetUtils.isLiteral(w)) {
                        flipBitLiteral |= w;
                    } else if (ConciseSetUtils.isZeroSequence(w)) {
                        flipBitLiteral |= ConciseSetUtils.getLiteralFromZeroSeqFlipBit(w);
                    } else {
                        assert ConciseSetUtils.isOneSequence(w);
                        flipBitLiteral |= ConciseSetUtils.getLiteralFromOneSeqFlipBit(w);
                    }
                }
                i.advanceTo(itr.wordsWalked);
                if (i.hasNext()) {
                    i.word = i.next();
                    changedIterators.add(i);
                }
            }
            // advance longest one literal forward and push result back to priority queue
            // if a flip bit is still needed, put it in the correct position
            int newWord = word & 0xC1FFFFFF;
            if (flipBitLiteral != ConciseSetUtils.ALL_ONES_LITERAL) {
                flipBitLiteral ^= ConciseSetUtils.ALL_ONES_LITERAL;
                int position = Integer.numberOfTrailingZeros(flipBitLiteral) + 1;
                newWord |= (position << 25);
            }
            addAndCompact(retVal, newWord);
            currIndex = itr.wordsWalked;
            if (itr.hasNext()) {
                itr.word = itr.next();
                changedIterators.add(itr);
            }
        }
        theQ.addAll(changedIterators);
        changedIterators.clear();
    }
    if (retVal.isEmpty()) {
        return new ImmutableConciseSet();
    }
    return new ImmutableConciseSet(IntBuffer.wrap(retVal.toArray()));
}
Also used : ArrayList(java.util.ArrayList) PriorityQueue(java.util.PriorityQueue) IntList(io.druid.extendedset.utilities.IntList)

Example 29 with PriorityQueue

use of java.util.PriorityQueue in project guava by google.

the class MinMaxPriorityQueueTest method testCorrectOrdering_randomAccess.

public void testCorrectOrdering_randomAccess() {
    long seed = new Random().nextLong();
    Random random = new Random(seed);
    PriorityQueue<Integer> control = new PriorityQueue<Integer>();
    MinMaxPriorityQueue<Integer> q = MinMaxPriorityQueue.create();
    for (int i = 0; i < 73; i++) {
        // 73 is a childless uncle case.
        Integer element = random.nextInt();
        control.add(element);
        assertTrue(q.add(element));
    }
    assertTrue("State " + Arrays.toString(q.toArray()), q.isIntact());
    for (int i = 0; i < 500000; i++) {
        if (random.nextBoolean()) {
            Integer element = random.nextInt();
            control.add(element);
            q.add(element);
        } else {
            assertEquals("Using seed " + seed, control.poll(), q.pollFirst());
        }
    }
    while (!control.isEmpty()) {
        assertEquals("Using seed " + seed, control.poll(), q.pollFirst());
    }
    assertTrue(q.isEmpty());
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Random(java.util.Random) PriorityQueue(java.util.PriorityQueue)

Example 30 with PriorityQueue

use of java.util.PriorityQueue in project HanLP by hankcs.

the class MinimumSpanningTreeParser method parse.

@Override
public CoNLLSentence parse(List<Term> termList) {
    if (termList == null || termList.size() == 0)
        return null;
    termList.add(0, new Term("##核心##", Nature.begin));
    Node[] nodeArray = new Node[termList.size()];
    Iterator<Term> iterator = termList.iterator();
    for (int i = 0; i < nodeArray.length; ++i) {
        nodeArray[i] = new Node(iterator.next(), i);
    }
    Edge[][] edges = new Edge[nodeArray.length][nodeArray.length];
    for (int i = 0; i < edges.length; ++i) {
        for (int j = 0; j < edges[i].length; ++j) {
            if (i != j) {
                edges[j][i] = makeEdge(nodeArray, i, j);
            }
        }
    }
    // 最小生成树Prim算法
    int max_v = nodeArray.length * (nodeArray.length - 1);
    float[] mincost = new float[max_v];
    Arrays.fill(mincost, Float.MAX_VALUE / 3);
    boolean[] used = new boolean[max_v];
    Arrays.fill(used, false);
    used[0] = true;
    PriorityQueue<State> que = new PriorityQueue<State>();
    // 找虚根的唯一孩子
    float minCostToRoot = Float.MAX_VALUE;
    Edge firstEdge = null;
    Edge[] edgeResult = new Edge[termList.size() - 1];
    for (Edge edge : edges[0]) {
        if (edge == null)
            continue;
        if (minCostToRoot > edge.cost) {
            firstEdge = edge;
            minCostToRoot = edge.cost;
        }
    }
    if (firstEdge == null)
        return null;
    que.add(new State(minCostToRoot, firstEdge.from, firstEdge));
    while (!que.isEmpty()) {
        State p = que.poll();
        int v = p.id;
        if (used[v] || p.cost > mincost[v])
            continue;
        used[v] = true;
        if (p.edge != null) {
            //                System.out.println(p.edge.from + " " + p.edge.to + p.edge.label);
            edgeResult[p.edge.from - 1] = p.edge;
        }
        for (Edge e : edges[v]) {
            if (e == null)
                continue;
            if (mincost[e.from] > e.cost) {
                mincost[e.from] = e.cost;
                que.add(new State(mincost[e.from], e.from, e));
            }
        }
    }
    CoNLLWord[] wordArray = new CoNLLWord[termList.size() - 1];
    for (int i = 0; i < wordArray.length; ++i) {
        wordArray[i] = new CoNLLWord(i + 1, nodeArray[i + 1].word, nodeArray[i + 1].label);
        wordArray[i].DEPREL = edgeResult[i].label;
    }
    for (int i = 0; i < edgeResult.length; ++i) {
        int index = edgeResult[i].to - 1;
        if (index < 0) {
            wordArray[i].HEAD = CoNLLWord.ROOT;
            continue;
        }
        wordArray[i].HEAD = wordArray[index];
    }
    return new CoNLLSentence(wordArray);
}
Also used : Node(com.hankcs.hanlp.dependency.common.Node) Term(com.hankcs.hanlp.seg.common.Term) PriorityQueue(java.util.PriorityQueue) State(com.hankcs.hanlp.dependency.common.State) CoNLLWord(com.hankcs.hanlp.corpus.dependency.CoNll.CoNLLWord) CoNLLSentence(com.hankcs.hanlp.corpus.dependency.CoNll.CoNLLSentence) Edge(com.hankcs.hanlp.dependency.common.Edge)

Aggregations

PriorityQueue (java.util.PriorityQueue)51 ArrayList (java.util.ArrayList)16 List (java.util.List)10 Map (java.util.Map)9 HashMap (java.util.HashMap)7 LinkedList (java.util.LinkedList)5 File (java.io.File)4 IOException (java.io.IOException)4 Entry (java.util.Map.Entry)4 Random (java.util.Random)4 BytesRef (org.apache.lucene.util.BytesRef)4 AbstractMapTable (com.ctriposs.sdb.table.AbstractMapTable)3 ScoredObject (edu.stanford.nlp.util.ScoredObject)3 Comparator (java.util.Comparator)3 Set (java.util.Set)3 FCMapTable (com.ctriposs.sdb.table.FCMapTable)2 HashMapTable (com.ctriposs.sdb.table.HashMapTable)2 IMapEntry (com.ctriposs.sdb.table.IMapEntry)2 MMFMapTable (com.ctriposs.sdb.table.MMFMapTable)2 Type (com.facebook.presto.spi.type.Type)2