题解:P7133 小 P 的星空

· · 题解

题目链接

前言

很好的一道题,写了两个小时,还看了题解,直接退役,所以写篇题解理理思路。

思路

可以将 x 轴和 y 轴的正负半轴单独取出来成为新的“象限”,操作过后总共就有 8 个象限了。然后将每个点排序,我是以 x 轴的正半轴为起点逆时针排的序,就是这样:

可以算出第一象限到任意一个点可以扫过多少个点,然后差分一下就好了。

然后问题变成了如何求第一象限到任意一个点(询问的点,可以不在 星星 中)可以扫过多少个点。排序后的点具有单调性,所以可以用二分处理,直接用 lower_bound 和 upperbound 就行了。

代码

#include <bits/stdc++.h>
#define int long long
using namespace std;

const int M = 1e5 + 5;

int n, m;

struct node {
    int x, y, q;

    bool operator< (const node &t) const {
        if(q != t.q) return q < t.q;
        if(q & 1) return 0;
        if(q == 2 || q == 6) return x * t.y > y * t.x;
        else return x * t.y < y * t.x;
        // 其实就是 y / x 和 t.y / t.x 的变形,因为直接求斜率精度会爆  
    }
} a[M];

int get_q(dou x, int y) { // 获取点的象限 
    if(x > 0 && y == 0) return 1;
    if(x > 0 && y > 0) return 2;
    if(x == 0 && y > 0) return 3;
    if(x < 0 && y > 0) return 4;
    if(x < 0 && y == 0) return 5;
    if(x < 0 && y < 0) return 6;
    if(x == 0 && y < 0) return 7;
    if(x > 0 && y < 0) return 8;
}

node type(int x, int y) { return {abs(x), abs(y), get_q(x, y)}; }

struct line { int s, t, w; };

line count(node t) {
    line res;
    // s 表示小于等于 t 的第一个点,因为重载了 <,所以可以直接用 lower_bound 
    res.s = lower_bound(a + 1, a + n + 1, t) - a;

    // t 表示最后一个等于 t 的点 
    res.t = upper_bound(a + 1, a + n + 1, t) - a - 1;

    // w 表示与这个点在同一直线上的点数 
    res.w = res.t - res.s + 1;
    return res;
}

int main() {
    scanf("%lld%lld", &n, &m);
    int x, y;
    for(int i = 1; i <= n; i++) {
        scanf("%lld%lld", &x, &y);
        a[i] = type(x, y);
    }
    sort(a + 1, a + n + 1);
    line now = count(type(1, 0));
    while(m--) {
        scanf("%lld%lld", &x, &y);
        line to = count(type(x, y));
        int tmp = to.s - now.t - 1;
        // tmp 表示的是 now 到 to 之间的星星数,不包括 now 和 to 所在的直线 
        if(tmp < 0) tmp += n;
        printf("%lld\n", max(n - tmp, tmp + now.w + to.w));
        // 可以从两个方向转 
        now = to;
    }
    return 0;
}