AcWing 1238. 日志统计(双指针)

Problem

第九届蓝桥杯的题目,暴力会超时,这里用双指针优化。

import java.io.*;
import java.util.Arrays;

public class Main {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static PrintWriter pw = new PrintWriter(System.out);
    static int n, d, k;
    static int N = 100010;
    static Pii[] piis = new Pii[N];
    static int cnt[] = new int[N];
    static boolean st[] = new boolean[N];

    public static void main(String[] args) throws IOException {

        String s[] = br.readLine().split(" ");
        n = Integer.parseInt(s[0]);
        d = Integer.parseInt(s[1]);
        k = Integer.parseInt(s[2]);
        for (int i = 0; i < n; i++) {
            s = br.readLine().split(" ");
            piis[i] = new Pii(Integer.parseInt(s[0]), Integer.parseInt(s[1]));
        }

        Arrays.sort(piis, 0, n);

        for (int i = 0, j = 0; i < n; i++) {
            int id = piis[i].id;
            cnt[id]++;
            while (piis[i].time - piis[j].time >= d) {
                cnt[piis[j].id]--;
                j++;
            }
            if (cnt[id] >= k) st[id] = true;
        }

        for (int i = 0; i <= 100000; i++)
            if (st[i])
                pw.println(i);

        pw.flush();
        pw.close();
        br.close();
    }
}

class Pii implements Comparable<Pii> {
    int time, id;

    public Pii(int time, int id) {
        this.time = time;
        this.id = id;
    }

    @Override
    public int compareTo(Pii pii) {
        return this.time - pii.time;
    }
}
发布了167 篇原创文章 · 获赞 3 · 访问量 3409

猜你喜欢

转载自blog.csdn.net/qq_43515011/article/details/104538009