20210827-PQ

递推(我从哪里来):dp[i] = Max[i-K,i-1] + d[i], 通过PQ获取Max[i-K,i-1]

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.Comparator;
import java.util.PriorityQueue;

public class SolutionPQ {
    
    
    public static void main(String[] args) throws IOException {
    
    
        in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        int T = nextInt();
        for (int i = 1; i <= 300000; i++) dp[i] = new Stone(i);
        for (int tc = 1; tc <= T; tc++) {
    
    
            work();
            System.out.println("#" + tc + " " + dp[N].val);
        }
    }

    static void work() throws IOException {
    
    
        N = nextInt();
        K = nextInt();
        for (int i = 1; i <= N; i++) d[i] = nextInt();
        pq.add(dp[1].set(d[1]));
        for (int i = 2; i <= N; i++) {
    
    
            int start = i - K;
            while (!pq.isEmpty() && pq.peek().pos < start) pq.poll();
            pq.add(dp[i].set(pq.peek().val + d[i]));
        }
        pq.clear();
    }

    static int nextInt() throws IOException {
    
    
        in.nextToken();
        return (int) in.nval;
    }

    static final int[] d = new int[300003];
    static final Stone[] dp = new Stone[300003];
    static final PriorityQueue<Stone> pq = new PriorityQueue<>(new Comparator<Stone>() {
    
    
        @Override
        public int compare(Stone o1, Stone o2) {
    
    
            return Long.compare(o2.val, o1.val);
        }
    });
    static StreamTokenizer in;
    static int N, K;

    static class Stone {
    
    
        int pos;
        long val;

        Stone(int i) {
    
    
            pos = i;
            val = 0;
        }

        Stone set(long v) {
    
    
            this.val = v;
            return this;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/awp0011/article/details/119962223
pq