[https://atcoder.jp/contests/abc234/tasks/abc234_d Prefix K-th Max] 最小堆实现
Problem Statement
Given are a permutation P=(P_1,P_2,\ldots,P_N)P=(P1,P2,…,PN) of (1,2,\ldots,N)(1,2,…,N) and a positive integer KK.
For each i=K,K+1,\ldots,Ni=K,K+1,…,N, find the following.
- The KK-th greatest value among the first ii terms of PP.
Constraints
- 1 \leq K \leq N \leq 5 \times 10^51≤K≤N≤5×105
- (P_1,P_2,\ldots,P_N)(P1,P2,…,PN) is a permutation of (1,2,\ldots,N)(1,2,…,N).
- All values in input are integers
解法:
这就是1个TOPK问题。
java的最小堆、最大堆可以使用PriorityQueue<Integer>
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.PriorityQueue; import java.util.TreeSet; public class Main { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int N,K; String[] words = reader.readLine().split("\\s+"); N = Integer.parseInt(words[0]); K = Integer.parseInt(words[1]); int[] P = new int[N]; words = reader.readLine().split("\\s+"); for(int i=0;i<N;i++){ P[i] = Integer.valueOf(words[i]); } PriorityQueue<Integer> pq = new PriorityQueue<>(K); for(int i =0;i<K;i++){ pq.add(P[i]); } StringBuilder sb = new StringBuilder(); sb.append(pq.peek()+"\n"); for(int i=K;i<N;i++){ int val = P[i]; if( val > pq.peek()){ pq.poll(); pq.add(val); } sb.append(pq.peek()+"\n"); // System.out.println(pq.peek()); } System.out.println(sb); reader.close(); } }

浙公网安备 33010602011771号